How does Django Know the Order to Render Form Fields?

后端 未结 14 1447
不知归路
不知归路 2020-11-28 05:21

If I have a Django form such as:

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = fo         


        
14条回答
  •  悲哀的现实
    2020-11-28 06:10

    [NOTE: this answer is now pretty completely outdated - please see the discussion below it, and more recent answers].

    If f is a form, its fields are f.fields, which is a django.utils.datastructures.SortedDict (it presents the items in the order they are added). After form construction f.fields has a keyOrder attribute, which is a list containing the field names in the order they should be presented. You can set this to the correct ordering (though you need to exercise care to ensure you don't omit items or add extras).

    Here's an example I just created in my current project:

    class PrivEdit(ModelForm):
        def __init__(self, *args, **kw):
            super(ModelForm, self).__init__(*args, **kw)
            self.fields.keyOrder = [
                'super_user',
                'all_districts',
                'multi_district',
                'all_schools',
                'manage_users',
                'direct_login',
                'student_detail',
                'license']
        class Meta:
            model = Privilege
    

提交回复
热议问题