Django forms, inheritance and order of form fields

前端 未结 11 1793
终归单人心
终归单人心 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条回答
  •  生来不讨喜
    2020-12-12 12:52

    Based on an answer by @akaihola and updated to work with latest Django 1.5 as self.fields.insert is being depreciated.

    from easycontactus.forms import *
    from django import forms
    class  CustomEasyContactUsForm(EasyContactUsForm):
        ### form settings and configuration
        CAPTHCA_PHRASE = 'igolf'
    
        ### native methods
        def __init__(self, *args, **kwargs):
            super(CustomEasyContactUsForm, self).__init__(*args, **kwargs)
            # re-order placement of added attachment field 
            self.fields.keyOrder.insert(self.fields.keyOrder.index('captcha'),
                                        self.fields.keyOrder.pop(self.fields.keyOrder.index('attachment'))
                                        )
    
        ### field defintitions
        attachment = forms.FileField()
    

    In the above we are extending an EasyContactUsForm base class as it is defined in django-easycontactus package.

提交回复
热议问题