Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I control the order of form fields in Django?

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?

like image 377
realtime Avatar asked Dec 07 '16 21:12

realtime


1 Answers

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. If field_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 to None without having to redefine ordering.

You can also use the Form.field_order argument to a Form to override the field order. If a Form defines field_order and you include field_order when instantiating the Form, then the latter field_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 in field_order.

like image 92
Adam Taylor Avatar answered Nov 18 '22 01:11

Adam Taylor