Django forms, inheritance and order of form fields

前端 未结 11 1798
终归单人心
终归单人心 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条回答
  •  猫巷女王i
    2020-12-12 13:11

    It appears that at some point the underlying structure of field order was changed from a django specific SordedDict to a python standard OrderedDict

    Thus, in 1.7 I had to do the following:

    from collections import OrderedDict
    
    class MyForm(forms.Form):
    
        def __init__(self, *args, **kwargs):
            super(MyForm, self).__init__(*args, **kwargs)
            original_fields = self.fields
            new_order = OrderedDict()
            for key in ['first', 'second', ... 'last']:
                new_order[key] = original_fields[key]
            self.fields = new_order
    

    I'm sure someone could golf that into two or three lines, but for S.O. purposes I think clearly showing how it works is better than cleaver.

提交回复
热议问题