Python – How does Django Know the Order to Render Form Fields

djangodjango-formspython

If I have a Django form such as:

class ContactForm(forms.Form):
    subject = forms.CharField(max_length=100)
    message = forms.CharField()
    sender = forms.EmailField()

And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.

My question is how does Django know the order that class variables where defined?

(Also how do I override this order, for example when I want to add a field from the classe's init method?)

Best Answer

New to Django 1.9 is Form.field_order and Form.order_fields().

# forms.Form example
class SignupForm(forms.Form):

    password = ...
    email = ...
    username = ...

    field_order = ['username', 'email', 'password']


# forms.ModelForm example
class UserAccount(forms.ModelForm):

    custom_field = models.CharField(max_length=254)

    def Meta:
        model = User
        fields = ('username', 'email')

    field_order = ['username', 'custom_field', 'password']