PageRenderTime 99ms CodeModel.GetById 41ms app.highlight 38ms RepoModel.GetById 12ms app.codeStats 0ms

/django/contrib/admin/helpers.py

https://code.google.com/p/mango-py/
Python | 353 lines | 350 code | 3 blank | 0 comment | 0 complexity | 47c0e31cb5e2ddf790d10a93cf800d96 MD5 | raw file
  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.form.base_fields:
102                is_inline = getattr(self.form.base_fields[field], 'is_inline', False)
103                is_disabled = getattr(self.form.base_fields[field], 'is_disabled', False)
104            else:
105                is_inline = False
106                is_disabled = False
107                
108            if field in self.readonly_fields:
109                yield AdminReadonlyField(self.form, field, is_first=(i == 0),
110                    model_admin=self.model_admin, is_inline=is_inline)
111            else:
112                yield AdminField(self.form, field, is_first=(i == 0), is_inline=is_inline)
113
114    def errors(self):
115        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'))
116
117class AdminField(object):
118    def __init__(self, form, field, is_first, is_inline=False):
119        self.field = form[field] # A django.forms.BoundField instance
120        self.is_first = is_first # Whether this field is first on the line
121        self.is_checkbox = isinstance(self.field.field.widget, forms.CheckboxInput)
122        self.is_inline = is_inline
123
124    def label_tag(self):
125        classes = []
126        if self.is_checkbox:
127            classes.append(u'vCheckboxLabel')
128            contents = force_unicode(escape(self.field.label))
129        else:
130            contents = force_unicode(escape(self.field.label)) + u':'
131        if self.field.field.required:
132            classes.append(u'required')
133        if not self.is_first:
134            classes.append(u'inline')
135        attrs = classes and {'class': u' '.join(classes)} or {}
136        return self.field.label_tag(contents=contents, attrs=attrs)
137
138    def errors(self):
139        return mark_safe(self.field.errors.as_ul())
140
141class AdminReadonlyField(object):
142    def __init__(self, form, field, is_first, model_admin=None, is_inline=False):
143        label = label_for_field(field, form._meta.model, model_admin)
144        # Make self.field look a little bit like a field. This means that
145        # {{ field.name }} must be a useful class name to identify the field.
146        # For convenience, store other field-related data here too.
147        if callable(field):
148            class_name = field.__name__ != '<lambda>' and field.__name__ or ''
149        else:
150            class_name = field
151        self.field = {
152            'name': class_name,
153            'label': label,
154            'field': field,
155            'help_text': help_text_for_field(class_name, form._meta.model)
156        }
157        self.form = form
158        self.model_admin = model_admin
159        self.is_first = is_first
160        self.is_checkbox = False
161        self.is_readonly = True
162        self.is_inline = is_inline
163
164    def label_tag(self):
165        attrs = {}
166        if not self.is_first:
167            attrs["class"] = "inline"
168        label = self.field['label']
169        contents = capfirst(force_unicode(escape(label))) + u":"
170        return mark_safe('<label%(attrs)s>%(contents)s</label>' % {
171            "attrs": flatatt(attrs),
172            "contents": contents,
173        })
174
175    def contents(self):
176        from django.contrib.admin.templatetags.admin_list import _boolean_icon
177        from django.contrib.admin.views.main import EMPTY_CHANGELIST_VALUE
178        field, obj, model_admin = self.field['field'], self.form.instance, self.model_admin
179        try:
180            f, attr, value = lookup_field(field, obj, model_admin)
181        except (AttributeError, ValueError, ObjectDoesNotExist):
182            result_repr = EMPTY_CHANGELIST_VALUE
183        else:
184            if f is None:
185                boolean = getattr(attr, "boolean", False)
186                if boolean:
187                    result_repr = _boolean_icon(value)
188                else:
189                    result_repr = smart_unicode(value)
190                    if getattr(attr, "allow_tags", False):
191                        result_repr = mark_safe(result_repr)
192            else:
193                if value is None:
194                    result_repr = EMPTY_CHANGELIST_VALUE
195                elif isinstance(f.rel, ManyToManyRel):
196                    result_repr = ", ".join(map(unicode, value.all()))
197                else:
198                    result_repr = display_for_field(value, f)
199        return conditional_escape(result_repr)
200
201class InlineAdminFormSet(object):
202    """
203    A wrapper around an inline formset for use in the admin system.
204    """
205    def __init__(self, inline, formset, fieldsets, readonly_fields=None, model_admin=None):
206        self.opts = inline
207        self.formset = formset
208        self.fieldsets = fieldsets
209        self.model_admin = model_admin
210        if readonly_fields is None:
211            readonly_fields = ()
212        self.readonly_fields = readonly_fields
213
214    def __iter__(self):
215        for form, original in zip(self.formset.initial_forms, self.formset.get_queryset()):
216            yield InlineAdminForm(self.formset, form, self.fieldsets,
217                self.opts.prepopulated_fields, original, self.readonly_fields,
218                model_admin=self.opts)
219        for form in self.formset.extra_forms:
220            yield InlineAdminForm(self.formset, form, self.fieldsets,
221                self.opts.prepopulated_fields, None, self.readonly_fields,
222                model_admin=self.opts)
223        yield InlineAdminForm(self.formset, self.formset.empty_form,
224            self.fieldsets, self.opts.prepopulated_fields, None,
225            self.readonly_fields, model_admin=self.opts)
226
227    def fields(self):
228        fk = getattr(self.formset, "fk", None)
229        for i, field in enumerate(flatten_fieldsets(self.fieldsets)):
230            if fk and fk.name == field:
231                continue
232            if field in self.readonly_fields:
233                yield {
234                    'label': label_for_field(field, self.opts.model, self.opts),
235                    'widget': {
236                        'is_hidden': False
237                    },
238                    'required': False
239                }
240            else:
241                yield self.formset.form.base_fields[field]
242
243    def _media(self):
244        media = self.opts.media + self.formset.media
245        for fs in self:
246            media = media + fs.media
247        return media
248    media = property(_media)
249
250class InlineAdminForm(AdminForm):
251    """
252    A wrapper around an inline form for use in the admin system.
253    """
254    def __init__(self, formset, form, fieldsets, prepopulated_fields, original,
255      readonly_fields=None, model_admin=None):
256        self.formset = formset
257        self.model_admin = model_admin
258        self.original = original
259        if original is not None:
260            self.original_content_type_id = ContentType.objects.get_for_model(original).pk
261        self.show_url = original and hasattr(original, 'get_absolute_url')
262        super(InlineAdminForm, self).__init__(form, fieldsets, prepopulated_fields,
263            readonly_fields, model_admin)
264
265    def __iter__(self):
266        for name, options in self.fieldsets:
267            yield InlineFieldset(self.formset, self.form, name,
268                self.readonly_fields, model_admin=self.model_admin, **options)
269
270    def has_auto_field(self):
271        if self.form._meta.model._meta.has_auto_field:
272            return True
273        # Also search any parents for an auto field.
274        for parent in self.form._meta.model._meta.get_parent_list():
275            if parent._meta.has_auto_field:
276                return True
277        return False
278
279    def field_count(self):
280        # tabular.html uses this function for colspan value.
281        num_of_fields = 0
282        if self.has_auto_field():
283            num_of_fields += 1
284        num_of_fields += len(self.fieldsets[0][1]["fields"])
285        if self.formset.can_order:
286            num_of_fields += 1
287        if self.formset.can_delete:
288            num_of_fields += 1
289        return num_of_fields
290
291    def pk_field(self):
292        return AdminField(self.form, self.formset._pk_field.name, False)
293
294    def fk_field(self):
295        fk = getattr(self.formset, "fk", None)
296        if fk:
297            return AdminField(self.form, fk.name, False)
298        else:
299            return ""
300
301    def deletion_field(self):
302        from django.forms.formsets import DELETION_FIELD_NAME
303        return AdminField(self.form, DELETION_FIELD_NAME, False)
304
305    def ordering_field(self):
306        from django.forms.formsets import ORDERING_FIELD_NAME
307        return AdminField(self.form, ORDERING_FIELD_NAME, False)
308
309class InlineFieldset(Fieldset):
310    def __init__(self, formset, *args, **kwargs):
311        self.formset = formset
312        super(InlineFieldset, self).__init__(*args, **kwargs)
313
314    def __iter__(self):
315        fk = getattr(self.formset, "fk", None)
316        for field in self.fields:
317            if fk and fk.name == field:
318                continue
319            yield Fieldline(self.form, field, self.readonly_fields,
320                model_admin=self.model_admin)
321
322class AdminErrorList(forms.util.ErrorList):
323    """
324    Stores all errors for the form/formsets in an add/change stage view.
325    """
326    def __init__(self, form, inline_formsets):
327        if form.is_bound:
328            self.extend(form.errors.values())
329            for inline_formset in inline_formsets:
330                self.extend(inline_formset.non_form_errors())
331                for errors_in_inline_form in inline_formset.errors:
332                    self.extend(errors_in_inline_form.values())
333
334def normalize_fieldsets(fieldsets):
335    """
336    Make sure the keys in fieldset dictionaries are strings. Returns the
337    normalized data.
338    """
339    result = []
340    for name, options in fieldsets:
341        result.append((name, normalize_dictionary(options)))
342    return result
343
344def normalize_dictionary(data_dict):
345    """
346    Converts all the keys in "data_dict" to strings. The keys must be
347    convertible using str().
348    """
349    for key, value in data_dict.items():
350        if not isinstance(key, str):
351            del data_dict[key]
352            data_dict[str(key)] = value
353    return data_dict