﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
8888	fields_for_model() should produce fields in the same order as in parameter 'fields'	andrewl	nobody	"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)
}}}"		closed	Core (Other)	1.0		duplicate	form, field, order		Accepted	0	0	0	0	0	0
