How does Django Know the Order to Render Form Fields?

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

    I went ahead and answered my own question. Here's the answer for future reference:

    In Django form.py does some dark magic using the __new__ method to load your class variables ultimately into self.fields in the order defined in the class. self.fields is a Django SortedDict instance (defined in datastructures.py).

    So to override this, say in my example you wanted sender to come first but needed to add it in an init method, you would do:

    class ContactForm(forms.Form):
        subject = forms.CharField(max_length=100)
        message = forms.CharField()
        def __init__(self,*args,**kwargs):
            forms.Form.__init__(self,*args,**kwargs)
            #first argument, index is the position of the field you want it to come before
            self.fields.insert(0,'sender',forms.EmailField(initial=str(time.time())))
    
    0 讨论(0)
  • 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']
    
    0 讨论(0)
提交回复
热议问题