Ticket #17911: helpers.py

File helpers.py, 13.0 KB (added by justin.r.donnelly@…, 13 years ago)

modified contrib/admin/helpers.py

Line 
1from django import forms
2from django.conf import settings
3from django.contrib.admin.util import (flatten_fieldsets, lookup_field,
4 display_for_field, label_for_field, help_text_for_field)
5from django.contrib.contenttypes.models import ContentType
6from django.core.exceptions import ObjectDoesNotExist
7from django.db.models.fields.related import ManyToManyRel
8from django.forms.util import flatatt
9from django.template.defaultfilters import capfirst
10from django.utils.encoding import force_unicode, smart_unicode
11from django.utils.html import escape, conditional_escape
12from django.utils.safestring import mark_safe
13from django.utils.translation import ugettext_lazy as _
14
15
16ACTION_CHECKBOX_NAME = '_selected_action'
17
18class ActionForm(forms.Form):
19 action = forms.ChoiceField(label=_('Action:'))
20 select_across = forms.BooleanField(label='', required=False, initial=0,
21 widget=forms.HiddenInput({'class': 'select-across'}))
22
23checkbox = forms.CheckboxInput({'class': 'action-select'}, lambda value: False)
24
25class AdminForm(object):
26 def __init__(self, form, fieldsets, prepopulated_fields, readonly_fields=None, model_admin=None):
27 self.form, self.fieldsets = form, normalize_fieldsets(fieldsets)
28 self.prepopulated_fields = [{
29 'field': form[field_name],
30 'dependencies': [form[f] for f in dependencies]
31 } for field_name, dependencies in prepopulated_fields.items()]
32 self.model_admin = model_admin
33 if readonly_fields is None:
34 readonly_fields = ()
35 self.readonly_fields = readonly_fields
36
37 def __iter__(self):
38 for name, options in self.fieldsets:
39 yield Fieldset(self.form, name,
40 readonly_fields=self.readonly_fields,
41 model_admin=self.model_admin,
42 **options
43 )
44
45 def first_field(self):
46 try:
47 fieldset_name, fieldset_options = self.fieldsets[0]
48 field_name = fieldset_options['fields'][0]
49 if not isinstance(field_name, basestring):
50 field_name = field_name[0]
51 return self.form[field_name]
52 except (KeyError, IndexError):
53 pass
54 try:
55 return iter(self.form).next()
56 except StopIteration:
57 return None
58
59 def _media(self):
60 media = self.form.media
61 for fs in self:
62 media = media + fs.media
63 return media
64 media = property(_media)
65
66class Fieldset(object):
67 def __init__(self, form, name=None, readonly_fields=(), fields=(), classes=(),
68 description=None, model_admin=None):
69 self.form = form
70 self.name, self.fields = name, fields
71 self.classes = u' '.join(classes)
72 self.description = description
73 self.model_admin = model_admin
74 self.readonly_fields = readonly_fields
75
76 def _media(self):
77 if 'collapse' in self.classes:
78 js = ['js/jquery.min.js', 'js/jquery.init.js', 'js/collapse.min.js']
79 return forms.Media(js=['%s%s' % (settings.ADMIN_MEDIA_PREFIX, url) for url in js])
80 return forms.Media()
81 media = property(_media)
82
83 def __iter__(self):
84 for field in self.fields:
85 yield Fieldline(self.form, field, self.readonly_fields, model_admin=self.model_admin)
86
87class Fieldline(object):
88 def __init__(self, form, field, readonly_fields=None, model_admin=None):
89 self.form = form # A django.forms.Form instance
90 if not hasattr(field, "__iter__"):
91 self.fields = [field]
92 else:
93 self.fields = field
94 self.model_admin = model_admin
95 if readonly_fields is None:
96 readonly_fields = ()
97 self.readonly_fields = readonly_fields
98
99 def __iter__(self):
100 for i, field in enumerate(self.fields):
101 if field in self.readonly_fields:
102 yield AdminReadonlyField(self.form, field, is_first=(i == 0),
103 model_admin=self.model_admin)
104 else:
105 yield AdminField(self.form, field, is_first=(i == 0))
106
107 def errors(self):
108 return mark_safe(u'\n'.join([self.form[f].errors.as_ul() for f in self.fields if f not in self.readonly_fields]).strip('\n'))
109
110class AdminField(object):
111 def __init__(self, form, field, is_first):
112 self.field = form[field] # A django.forms.BoundField instance
113 self.is_first = is_first # Whether this field is first on the line
114 self.is_checkbox = isinstance(self.field.field.widget, forms.CheckboxInput)
115
116 def label_tag(self):
117 classes = []
118 if self.is_checkbox:
119 classes.append(u'vCheckboxLabel')
120 contents = force_unicode(escape(self.field.label))
121 else:
122 contents = force_unicode(escape(self.field.label)) + u':'
123 if self.field.field.required:
124 classes.append(u'required')
125 if not self.is_first:
126 classes.append(u'inline')
127 attrs = classes and {'class': u' '.join(classes)} or {}
128 return self.field.label_tag(contents=contents, attrs=attrs)
129
130 def errors(self):
131 return mark_safe(self.field.errors.as_ul())
132
133class AdminReadonlyField(object):
134 def __init__(self, form, field, is_first, model_admin=None):
135 label = label_for_field(field, form._meta.model, model_admin)
136 # Make self.field look a little bit like a field. This means that
137 # {{ field.name }} must be a useful class name to identify the field.
138 # For convenience, store other field-related data here too.
139 if callable(field):
140 class_name = field.__name__ != '<lambda>' and field.__name__ or ''
141 else:
142 class_name = field
143 self.field = {
144 'name': class_name,
145 'label': label,
146 'field': field,
147 'help_text': help_text_for_field(class_name, form._meta.model)
148 }
149 self.form = form
150 self.model_admin = model_admin
151 self.is_first = is_first
152 self.is_checkbox = False
153 self.is_readonly = True
154
155 def label_tag(self):
156 attrs = {}
157 if not self.is_first:
158 attrs["class"] = "inline"
159 label = self.field['label']
160 contents = capfirst(force_unicode(escape(label))) + u":"
161 return mark_safe('<label%(attrs)s>%(contents)s</label>' % {
162 "attrs": flatatt(attrs),
163 "contents": contents,
164 })
165
166 def contents(self):
167 from django.contrib.admin.templatetags.admin_list import _boolean_icon
168 from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
169 field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin
170 try:
171 f, attr, value = lookup_field(field, obj, model_admin)
172 except (AttributeError, ValueError, ObjectDoesNotExist):
173 result_repr = EMPTY_CHANGELIST_VALUE
174 else:
175 if f is None:
176 boolean = getattr(attr, "boolean", False)
177 if boolean:
178 result_repr = _boolean_icon(value)
179 else:
180 result_repr = smart_unicode(value)
181 if getattr(attr, "allow_tags", False):
182 result_repr = mark_safe(result_repr)
183 else:
184 if isinstance(f.rel, ManyToManyRel) and value is not None:
185 result_repr = ", ".join(map(unicode, value.all()))
186 else:
187 result_repr = display_for_field(value, f)
188 return conditional_escape(result_repr)
189
190class InlineAdminFormSet(object):
191 """
192 A wrapper around an inline formset for use in the admin system.
193 """
194 def __init__(self, inline, formset, fieldsets, readonly_fields=None, model_admin=None):
195 self.opts = inline
196 self.formset = formset
197 self.fieldsets = fieldsets
198 self.model_admin = model_admin
199 if readonly_fields is None:
200 readonly_fields = ()
201 self.readonly_fields = readonly_fields
202
203 def __iter__(self):
204 for form, original in zip(self.formset.initial_forms, self.formset.get_queryset()):
205 yield InlineAdminForm(self.formset, form, self.fieldsets,
206 self.opts.prepopulated_fields, original, self.readonly_fields,
207 model_admin=self.opts)
208 for form in self.formset.extra_forms:
209 yield InlineAdminForm(self.formset, form, self.fieldsets,
210 self.opts.prepopulated_fields, None, self.readonly_fields,
211 model_admin=self.opts)
212 yield InlineAdminForm(self.formset, self.formset.empty_form,
213 self.fieldsets, self.opts.prepopulated_fields, None,
214 self.readonly_fields, model_admin=self.opts)
215
216 def fields(self):
217 fk = getattr(self.formset, "fk", None)
218 for i, field in enumerate(flatten_fieldsets(self.fieldsets)):
219 if fk and fk.name == field:
220 continue
221 if field in self.readonly_fields:
222 yield {
223 'label': label_for_field(field, self.opts.model, self.opts),
224 'widget': {
225 'is_hidden': False
226 },
227 'required': False
228 }
229 else:
230 yield self.formset.form.base_fields[field]
231
232 def _media(self):
233 media = self.opts.media + self.formset.media
234 for fs in self:
235 media = media + fs.media
236 return media
237 media = property(_media)
238
239class InlineAdminForm(AdminForm):
240 """
241 A wrapper around an inline form for use in the admin system.
242 """
243 def __init__(self, formset, form, fieldsets, prepopulated_fields, original,
244 readonly_fields=None, model_admin=None):
245 self.formset = formset
246 self.model_admin = model_admin
247 self.original = original
248 if original is not None:
249 self.original_content_type_id = ContentType.objects.get_for_model(original).pk
250 self.show_url = original and hasattr(original, 'get_absolute_url')
251 super(InlineAdminForm, self).__init__(form, fieldsets, prepopulated_fields,
252 readonly_fields, model_admin)
253
254 def __iter__(self):
255 for name, options in self.fieldsets:
256 yield InlineFieldset(self.formset, self.form, name,
257 self.readonly_fields, model_admin=self.model_admin, **options)
258
259 def has_auto_field(self):
260 if self.form._meta.model._meta.has_auto_field:
261 return True
262 # Also search any parents for an auto field.
263 for parent in self.form._meta.model._meta.get_parent_list():
264 if parent._meta.has_auto_field:
265 return True
266 return False
267
268 def field_count(self):
269 # tabular.html uses this function for colspan value.
270 num_of_fields = 0
271 if self.has_auto_field():
272 num_of_fields += 1
273 num_of_fields += len(self.fieldsets[0][1]["fields"])
274 if self.formset.can_order:
275 num_of_fields += 1
276 if self.formset.can_delete:
277 num_of_fields += 1
278 return num_of_fields
279
280 def pk_field(self):
281 return AdminField(self.form, self.formset._pk_field.name, False)
282
283 def fk_field(self):
284 fk = getattr(self.formset, "fk", None)
285 if fk:
286 return AdminField(self.form, fk.name, False)
287 else:
288 return ""
289
290 def deletion_field(self):
291 from django.forms.formsets import DELETION_FIELD_NAME
292 return AdminField(self.form, DELETION_FIELD_NAME, False)
293
294 def ordering_field(self):
295 from django.forms.formsets import ORDERING_FIELD_NAME
296 return AdminField(self.form, ORDERING_FIELD_NAME, False)
297
298class InlineFieldset(Fieldset):
299 def __init__(self, formset, *args, **kwargs):
300 self.formset = formset
301 super(InlineFieldset, self).__init__(*args, **kwargs)
302
303 def __iter__(self):
304 fk = getattr(self.formset, "fk", None)
305 for field in self.fields:
306 if fk and fk.name == field:
307 continue
308 yield Fieldline(self.form, field, self.readonly_fields,
309 model_admin=self.model_admin)
310
311class AdminErrorList(forms.util.ErrorList):
312 """
313 Stores all errors for the form/formsets in an add/change stage view.
314 """
315 def __init__(self, form, inline_formsets):
316 if form.is_bound:
317 self.extend(form.errors.values())
318 for inline_formset in inline_formsets:
319 self.extend(inline_formset.non_form_errors())
320 for errors_in_inline_form in inline_formset.errors:
321 self.extend(errors_in_inline_form.values())
322
323def normalize_fieldsets(fieldsets):
324 """
325 Make sure the keys in fieldset dictionaries are strings. Returns the
326 normalized data.
327 """
328 result = []
329 for name, options in fieldsets:
330 result.append((name, normalize_dictionary(options)))
331 return result
332
333def normalize_dictionary(data_dict):
334 """
335 Converts all the keys in "data_dict" to strings. The keys must be
336 convertible using str().
337 """
338 for key, value in data_dict.items():
339 if not isinstance(key, str):
340 del data_dict[key]
341 data_dict[str(key)] = value
342 return data_dict
Back to Top