Opened 10 years ago

Closed 9 years ago

Last modified 7 years ago

#8888 closed (duplicate)

fields_for_model() should produce fields in the same order as in parameter 'fields'

Reported by: andrewl Owned by: nobody
Component: Core (Other) Version: 1.0
Severity: Keywords: form, field, order
Cc: Triage Stage: Accepted
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: UI/UX:


As per the TODO on line 126 of django/forms/ "# TODO: if fields is provided, it would be nice to return fields in that order"

A simple solution would be to maintain a temporary dictionary of the field names vs form fields as they are created, then at the end reorder them as per the fields parameter using the dictionary.

The modified code below for the method works, though it admittedly creates and maintains the temporary dictionary even if 'fields' is not defined... which obviously is a tad wasteful in such a case (new lines in method marked with '>>>').

def fields_for_model(model, fields=None, exclude=None, formfield_callback=lambda f: f.formfield()):
    Returns a ``SortedDict`` containing form fields for the given model.

    ``fields`` is an optional list of field names. If provided, only the named
    fields will be included in the returned fields.

    ``exclude`` is an optional list of field names. If provided, the named
    fields will be excluded from the returned fields, even if they are listed
    in the ``fields`` argument.
    field_list = []
>>> temp_dict = {}
    opts = model._meta
    for f in opts.fields + opts.many_to_many:
        if not f.editable:
        if fields and not in fields:
        if exclude and in exclude:
        formfield = formfield_callback(f)
        if formfield:
>>>         temp_dict[] = formfield
            field_list.append((, formfield))
>>>     if fields:
>>>         # reorder to match ordering in 'fields' if it was provided
>>>         field_list = [(fn,temp_dict.get(fn)) for fn in fields if temp_dict.has_key(fn)]
    return SortedDict(field_list)

Attachments (1) (3.9 KB) - added by andrewl 10 years ago.
SVN diff for django/forms/

Download all attachments as: .zip

Change History (5)

comment:1 Changed 10 years ago by Russell Keith-Magee

Reporter: changed from anonymous to andrewl

Set the reporter since I know where this has come from.

Changed 10 years ago by andrewl

Attachment: added

SVN diff for django/forms/

comment:2 Changed 9 years ago by Jacob

milestone: 1.1
Triage Stage: UnreviewedAccepted

comment:3 Changed 9 years ago by Alex Gaynor

Resolution: duplicate
Status: newclosed

Marking as a dupe of #8164.

comment:4 Changed 7 years ago by Jacob

milestone: 1.1

Milestone 1.1 deleted

Note: See TracTickets for help on using tickets.
Back to Top