How does Django Know the Order to Render Form Fields?

后端 未结 14 1416
不知归路
不知归路 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:09

    If either fields = '__all__':

    class AuthorForm(ModelForm):
        class Meta:
            model = Author
            fields = '__all__'
    

    or exclude are used:

    class PartialAuthorForm(ModelForm):
        class Meta:
            model = Author
            exclude = ['title']
    

    Then Django references the order of fields as defined in the model. This just caught me out, so I thought I'd mention it. It's referenced in the ModelForm docs:

    If either of these are used, the order the fields appear in the form will be the order the fields are defined in the model, with ManyToManyField instances appearing last.

提交回复
热议问题