Reputation: 415
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?
Upvotes: 5
Views: 5228
Reputation: 4839
From the "Notes on field ordering" section of Django's forms API documentation:
There are several other ways to customize the order:
Form.field_order
By default
Form.field_order=None
, which retains the order in which you define the fields in your form class. Iffield_order
is 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 toNone
without having to redefine ordering.You can also use the
Form.field_order
argument to aForm
to override the field order. If aForm
definesfield_order
and you includefield_order
when instantiating theForm
, then the latterfield_order
will 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
.
Upvotes: 11