Django forms, inheritance and order of form fields

前端 未结 11 1768
终归单人心
终归单人心 2020-12-12 12:15

I\'m using Django forms in my website and would like to control the order of the fields.

Here\'s how I define my forms:

class edit_form(forms.Form):
         


        
11条回答
  •  既然无缘
    2020-12-12 12:59

    Alternate methods for changing the field order:

    Pop-and-insert:

    self.fields.insert(0, 'name', self.fields.pop('name'))
    

    Pop-and-append:

    self.fields['summary'] = self.fields.pop('summary')
    self.fields['description'] = self.fields.pop('description')
    

    Pop-and-append-all:

    for key in ('name', 'summary', 'description'):
        self.fields[key] = self.fields.pop(key)
    

    Ordered-copy:

    self.fields = SortedDict( [ (key, self.fields[key])
                                for key in ('name', 'summary' ,'description') ] )
    

    But Selene's approach from the Django CookBook still feels clearest of all.

提交回复
热议问题