Opened 16 years ago

Closed 15 years ago

Last modified 12 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: no UI/UX: no

Description

As per the TODO on line 126 of django/forms/models.py: "# 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:
            continue
        if fields and not f.name in fields:
            continue
        if exclude and f.name in exclude:
            continue
        formfield = formfield_callback(f)
        if formfield:
>>>         temp_dict[f.name] = formfield
            field_list.append((f.name, 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)

models.py.svn_diff (3.9 KB ) - added by andrewl 16 years ago.
SVN diff for django/forms/models.py

Download all attachments as: .zip

Change History (5)

comment:1 by Russell Keith-Magee, 16 years ago

Reporter: changed from anonymous to andrewl

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

by andrewl, 16 years ago

Attachment: models.py.svn_diff added

SVN diff for django/forms/models.py

comment:2 by Jacob, 15 years ago

milestone: 1.1
Triage Stage: UnreviewedAccepted

comment:3 by Alex Gaynor, 15 years ago

Resolution: duplicate
Status: newclosed

Marking as a dupe of #8164.

comment:4 by Jacob, 12 years ago

milestone: 1.1

Milestone 1.1 deleted

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