Ticket #5986: django-fields-order.patch

File django-fields-order.patch, 1.4 KB (added by emes, 7 years ago)

Second approach, with Form.Meta.fields_order

  • newforms/forms.py

     
    88from django.utils.html import escape
    99from django.utils.encoding import StrAndUnicode, smart_unicode, force_unicode
    1010from django.utils.safestring import mark_safe
     11from django.core.management.base import CommandError
    1112
    1213from fields import Field
    1314from widgets import TextInput, Textarea
     
    3839            if hasattr(base, 'base_fields'):
    3940                fields = base.base_fields.items() + fields
    4041
     42        # Sort by Meta.fields_order if present.
     43        # Raises CommandError if any of the fields is missing.
     44        if attrs.has_key('Meta') and hasattr(attrs['Meta'], 'fields_order'):
     45            def _indexcmp(x, y):
     46                errstr = "%s not present in %s.Meta.fields_order"
     47                try:
     48                    xindex = attrs['Meta'].fields_order.index(x[0])
     49                except ValueError:
     50                    raise CommandError, errstr % (x[0], name)
     51                try:
     52                    yindex = attrs['Meta'].fields_order.index(y[0])
     53                except ValueError:
     54                    raise CommandError, errstr % (y[0], name)
     55                return cmp(xindex, yindex)
     56            fields.sort(_indexcmp)
     57
    4158        attrs['base_fields'] = SortedDict(fields)
    4259        return type.__new__(cls, name, bases, attrs)
    4360
Back to Top