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?)
I went ahead and answered my own question. Here’s the answer for future reference:
In Django
form.pydoes some dark magic using the__new__method to load your class variables ultimately intoself.fieldsin the order defined in the class.self.fieldsis a DjangoSortedDictinstance (defined indatastructures.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: