Given that I have a generic form like this:
from django import forms
class TimesForm(forms.Form):
     hours = forms.DecimalField()
     description = forms.CharField()
     topic = forms.CharField()
And I want to render this form in html, what is the best way to dynamically control the order of appearance? In other words, the user should be able to control the order in which those input fields are displayed on the screen.
While I was able to iterate through the fields like this:
{% for field in form %}
{{field}}
{% endfor %}
I did not find a proper way to control the order of appearance of the input fields. How do I best do that?
From the "Notes on field ordering" section of Django's forms API documentation:
There are several other ways to customize the order:
Form.field_orderBy default
Form.field_order=None, which retains the order in which you define the fields in your form class. Iffield_orderis a list of field names, the fields are ordered as specified by the list and remaining fields are appended according to the default order. Unknown field names in the list are ignored. This makes it possible to disable a field in a subclass by setting it toNonewithout having to redefine ordering.You can also use the
Form.field_orderargument to aFormto override the field order. If aFormdefinesfield_orderand you includefield_orderwhen instantiating theForm, then the latterfield_orderwill have precedence.
Form.order_fields(field_order)You may rearrange the fields any time using
order_fields()with a list of field names as infield_order.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With