Django

Code

Ticket #8164: modelforms-fields-order.diff

File modelforms-fields-order.diff, 2.9 kB (added by Alex, 1 year ago)
  • a/django/forms/models.py

    old new  
    149149    fields will be excluded from the returned fields, even if they are listed 
    150150    in the ``fields`` argument. 
    151151    """ 
    152     # TODO: if fields is provided, it would be nice to return fields in that order 
    153152    field_list = [] 
    154153    opts = model._meta 
    155154    for f in opts.fields + opts.many_to_many: 
     
    162161        formfield = formfield_callback(f) 
    163162        if formfield: 
    164163            field_list.append((f.name, formfield)) 
    165     return SortedDict(field_list) 
     164    field_dict = SortedDict(field_list) 
     165    if fields: 
     166        field_dict.keyOrder = [f for f in fields if (not exclude) or (exclude and f not in exclude)] 
     167    return field_dict 
    166168 
    167169class ModelFormOptions(object): 
    168170    def __init__(self, options=None): 
  • a/docs/topics/forms/modelforms.txt

    old new  
    259259 
    2602602. Use the ``fields`` attribute of the ``ModelForm``'s inner ``Meta`` 
    261261   class.  This attribute, if given, should be a list of field names 
    262    to include in the form. 
     262   to include in the form.  The order of the items in ``fields`` will be the  
     263   order the field's appear in when rendered if ``fields`` is provided. 
    263264 
    2642653. Use the ``exclude`` attribute of the ``ModelForm``'s inner ``Meta`` 
    265266   class.  This attribute, if given, should be a list of field names 
  • a/tests/modeltests/model_forms/models.py

    old new  
    331331<tr><th><label for="id_slug">Slug:</label></th><td><input id="id_slug" type="text" name="slug" maxlength="20" /></td></tr> 
    332332<tr><th><label for="id_checkbox">Checkbox:</label></th><td><input type="checkbox" name="checkbox" id="id_checkbox" /></td></tr> 
    333333 
     334# test using fields to provide ordering to the fields 
     335>>> class CategoryForm(ModelForm): 
     336...     class Meta: 
     337...         model = Category 
     338...         fields = ['url', 'name'] 
     339 
     340>>> CategoryForm.base_fields.keys() 
     341['url', 'name'] 
     342 
     343>>> print CategoryForm() 
     344<tr><th><label for="id_url">The URL:</label></th><td><input id="id_url" type="text" name="url" maxlength="40" /></td></tr> 
     345<tr><th><label for="id_name">Name:</label></th><td><input id="id_name" type="text" name="name" maxlength="20" /></td></tr> 
     346 
    334347# Old form_for_x tests ####################################################### 
    335348 
    336349>>> from django.forms import ModelForm, CharField