Django forms, inheritance and order of form fields

前端 未结 11 1760
终归单人心
终归单人心 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 13:07

    I built a form 'ExRegistrationForm' inherited from the 'RegistrationForm' from Django-Registration-Redux. I faced two issues, one of which was reordering the fields on the html output page once the new form had been created.

    I solved them as follows:

    1. ISSUE 1: Remove Username from the Registration Form: In my_app.forms.py

        class ExRegistrationForm(RegistrationForm):
              #Below 2 lines extend the RegistrationForm with 2 new fields firstname & lastname
              first_name = forms.CharField(label=(u'First Name'))
              last_name = forms.CharField(label=(u'Last Name'))
    
              #Below 3 lines removes the username from the fields shown in the output of the this form
              def __init__(self, *args, **kwargs):
              super(ExRegistrationForm, self).__init__(*args, **kwargs)
              self.fields.pop('username')
    

    2. ISSUE 2: Make FirstName and LastName appear on top: In templates/registration/registration_form.html

    You can individually display the fields in the order that you want. This would help in case the number of fields are less, but not if you have a large number of fields where it becomes practically impossible to actually write them in the form.

         {% extends "base.html" %}
         {% load i18n %}
    
         {% block content %}
         
    {% csrf_token %} #The Default html is: {{ form.as_p }} , which can be broken down into individual elements as below for re-ordering.

    First Name: {{ form.first_name }}

    Last Name: {{ form.last_name }}

    Email: {{ form.email }}

    Password: {{ form.password1 }}

    Confirm Password: {{ form.password2 }}

    {% endblock %}

提交回复
热议问题