How does Django Know the Order to Render Form Fields?

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

    Fields are listed in the order they are defined in ModelClass._meta.fields. But if you want to change order in Form, you can do by using keyOrder function. For example :

    class ContestForm(ModelForm):
      class Meta:
        model = Contest
        exclude=('create_date', 'company')
    
      def __init__(self, *args, **kwargs):
        super(ContestForm, self).__init__(*args, **kwargs)
        self.fields.keyOrder = [
            'name',
            'description',
            'image',
            'video_link',
            'category']
    

提交回复
热议问题