Code

AJAXForeignKey: forms2.py

File forms2.py, 6.0 KB (added by Michael Axiak <axiak@…>, 7 years ago)

Makes more usable without JS, supports MSIE 6 and 5.5

Line 
1from django import oldforms
2from django.template.defaultfilters import addslashes
3from django.contrib.auth.models import User
4import re
5
6get_id_re = re.compile('\D*(\d+)\D$')
7
8class AjaxForeignKeyFormField(oldforms.FormField):
9    def __init__(self, field_name, field,
10                 is_required=False, validator_list=None,
11                 member_name=None, ajax_func = None, width=None):
12
13        self.field_name  = field_name
14        self.field       = field
15        self.is_required = is_required
16
17        if width is None:
18            self.width = '25em'
19        else:
20            self.width = width
21
22        if ajax_func is None:
23            self.ajax_func = 'ajax_autocomplete'
24        else:
25            self.ajax_func = ajax_func
26       
27        if validator_list is None:
28            validator_list = []
29
30        self.validator_list = validator_list
31
32    def extract_data(self, data):
33        return data.get(self.field.attname, '')
34
35
36    def render(self, data):
37        """
38        Renders the actual ajax widget.
39        """
40
41        old_init_val = init_val = data
42
43        if data:
44            objects = self.field.rel.to.objects.filter(pk = data)
45            if objects.count() == 1:
46                obj = objects[0]
47                if hasattr(obj, 'ajax_str'):
48                    init_val = obj.ajax_str() + " (%s)" % data
49                    old_init_val = str(obj)
50                else:
51                    old_init_val = init_val = obj.__str__() + " (%s)" % data
52        else:
53            data = init_val = ''
54
55
56        fn = self.field_name
57        related_model = self.field.rel.to
58        # espuser hack
59        if related_model == User:
60            model_module = 'esp.users.models'
61            model_name   = 'ESPUser'
62        else:
63            model_module = related_model.__module__
64            model_name   = related_model.__name__
65       
66        javascript = """
67<script type="text/javascript">
68<!--
69
70document.getElementById("id_%s").value = "%s";
71
72var %s_data = new YAHOO.widget.DS_XHR("/admin/ajax_autocomplete/",
73                                      ['result','ajax_str','id']);
74
75%s_data.scriptQueryParam  = "ajax_data";
76%s_data.scriptQueryAppend = "model_module=%s&model_name=%s&ajax_func=%s";
77%s_data.connTimeout = 3000;
78
79var autocomp__%s = new YAHOO.widget.AutoComplete("id_%s","id_%s__container",%s_data);
80
81autocomp__%s.allowBrowserAutocomplete = false;
82//autocomp__%s.typeAhead = true;
83autocomp__%s.animVert = true;
84autocomp__%s.queryDelay = .2;
85autocomp__%s.maxCacheEntries = 60;
86autocomp__%s.animSpeed = .5;
87autocomp__%s.useShadow = true;
88autocomp__%s.useIFrame = true;
89
90
91YAHOO.util.Event.addListener(window, "load", function (e) {
92  var elements = YAHOO.util.Dom.getElementsByClassName('add-another', 'a');
93  for (var i=0; i<elements.length; i++) {
94    elements[i].style.display = 'none';
95  }
96  var elements = YAHOO.util.Dom.getElementsByClassName('raw_id_admin', 'div');
97  for (var i=0; i< elements.length; i++) {
98     elements[i].style.display = 'none';
99     elements[i].style.visibility = 'hidden';
100  }
101
102  var elements = YAHOO.util.Dom.getElementsByClassName('form-row', 'div');
103  for (var i=0; i< elements.length; i++) {
104    elements[i].style.overflow = 'visible';
105    if (YAHOO.util.Dom.getElementsByClassName('yui_autocomplete','div', elements[i]).length > 0) {
106        elements[i].style.paddingBottom = '12.5em';
107    }
108  }
109});
110
111//-->
112</script>""" % \
113         (fn, addslashes(init_val),
114          fn, fn, fn, model_module, model_name, self.ajax_func,
115          fn, fn, fn, fn, fn, fn, fn, fn, fn, fn, fn, fn, fn)
116
117        css = """
118<style type="text/css">
119    /* Taken from Yahoo... */
120    #id_%s__yui_autocomplete {position:relative;width:%s;margin-bottom:1em;}/* set width of widget here*/
121    #id_%s__yui_autocomplete {z-index:0} /* for IE z-index of absolute divs inside relative divs issue */
122    #id_%s__yui_autocomplete input {_position:absolute;width:100%%;height:1.4em;z-index:0;} /* abs for ie quirks */
123    #id_%s__container {position:relative; width:100%%;top:-.1em;}
124    #id_%s__container .yui-ac-content {position:absolute;width:100%%;border:1px solid #ccc;background:#fff;overflow:hidden;z-index:9050;}
125    #id_%s__container .yui-ac-shadow {position:absolute;margin:.3em;width:100%%;background:#eee;z-index:8000;}
126    #id_%s__container ul {padding:5px 0;width:100%%; list-item-type: none;margin-left: 0; padding-left: 0;z-index:9000;}
127    #id_%s__container li {padding:0 5px;cursor:default;white-space:nowrap;padding-left: 0; margin-left: 0;}
128    #id_%s__container li.yui-ac-highlight {background:#9cf;z-index:9000;}
129    #id_%s__container li.yui-ac-prehighlight {background:#CCFFFF;z-index:9000;}
130    .yui-ac-bd { padding:0; margin: 0; z-index:9000;}
131</style>
132<!--[if lte IE 6]>
133<style type="text/css">
134    #id_%s__container { position: relative;top:2.3em; }
135</style>
136<![endif]-->
137""" % \
138        (fn,self.width,fn,fn,fn,fn,fn,fn,fn,fn,fn,fn)
139
140        html = """
141<div class="container" style="position: relative;">
142<div class="yui_autocomplete" id="id_%s__yui_autocomplete">
143  <input type="text" id="id_%s" name="%s" class="vCharField%s" value="%s" />
144  <div id="id_%s__container" class="yui_container"></div>
145</div>
146</div>
147<div class="raw_id_admin">
148  <a href="../../../datatree/datatree/" class="related-lookup" id="lookup_%s" onclick="return showRelatedObjectLookupPopup(this);">
149  <img src="/media/admin/img/admin/selector-search.gif" width="16" height="16" alt="Lookup" /></a>   
150   &nbsp;<strong>%s</strong>
151</div>
152""" % (fn,fn,fn,self.field.blank and ' required' or '',addslashes(data or ''),fn,
153       fn,old_init_val)
154
155        return css + html + javascript
156
157    def prepare(self, new_data):
158        id = new_data.get(self.field_name, None)
159        if id:
160            try:
161                id = int(id)
162            except ValueError:
163                match = get_id_re.match(id)
164                id = match.groups()[0]
165        new_data[self.field_name] = id