#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)
Change History (5)
comment:1 by , 16 years ago
Reporter: | changed from | to
---|
comment:2 by , 16 years ago
milestone: | → 1.1 |
---|---|
Triage Stage: | Unreviewed → Accepted |
comment:3 by , 16 years ago
Resolution: | → duplicate |
---|---|
Status: | new → closed |
Marking as a dupe of #8164.
Set the reporter since I know where this has come from.