diff --git a/django/forms/models.py b/django/forms/models.py index e6bbb98..d5eab82 100644 --- a/django/forms/models.py +++ b/django/forms/models.py @@ -149,7 +149,6 @@ def fields_for_model(model, fields=None, exclude=None, formfield_callback=lambda fields will be excluded from the returned fields, even if they are listed in the ``fields`` argument. """ - # TODO: if fields is provided, it would be nice to return fields in that order field_list = [] opts = model._meta for f in opts.fields + opts.many_to_many: @@ -162,7 +161,10 @@ def fields_for_model(model, fields=None, exclude=None, formfield_callback=lambda formfield = formfield_callback(f) if formfield: field_list.append((f.name, formfield)) - return SortedDict(field_list) + field_dict = SortedDict(field_list) + if fields: + field_dict.keyOrder = [f for f in fields if (not exclude) or (exclude and f not in exclude)] + return field_dict class ModelFormOptions(object): def __init__(self, options=None): diff --git a/docs/topics/forms/modelforms.txt b/docs/topics/forms/modelforms.txt index 50beea2..fe1e2a1 100644 --- a/docs/topics/forms/modelforms.txt +++ b/docs/topics/forms/modelforms.txt @@ -259,7 +259,8 @@ model fields: 2. Use the ``fields`` attribute of the ``ModelForm``'s inner ``Meta`` class. This attribute, if given, should be a list of field names - to include in the form. + to include in the form. The order of the items in ``fields`` will be the + order the field's appear in when rendered if ``fields`` is provided. 3. Use the ``exclude`` attribute of the ``ModelForm``'s inner ``Meta`` class. This attribute, if given, should be a list of field names diff --git a/tests/modeltests/model_forms/models.py b/tests/modeltests/model_forms/models.py index e12363c..613b075 100644 --- a/tests/modeltests/model_forms/models.py +++ b/tests/modeltests/model_forms/models.py @@ -331,6 +331,19 @@ We can also subclass the Meta inner class to change the fields list.