Reorder model form fields

I need to reorder the fields in a model that came from another base class. Could not find a solution. The "address" in the snippet below is always displayed at the beginning in the HTML template. How can I move it further with the created template? Thanks in advance.

class Address: street= ... city= ... class Customer(Address): name = ... ... class CustomerForm(ModelForm): def __init__(...) super(CustomerForm, self).__init__(*args, **kw) self.fields.keyOrder=[ 'name', 'Address', #<-- I want "Address" appear after the name in my template #<-- This obviously is not the right code. class Meta: model = Customer 

-P

+6
django django-models django-forms django-templates
source share
4 answers

Reordering is rather tedious:

 # django SortedDict stores ordering of its fields in this list-type attribute: keyorder = self.fields.keyOrder # Remove fields which we want to displace: keyorder.remove('street') keyorder.remove('city') # Get position where we want them to put in: i = keyorder.index('name') + 1 # Insert items back into the list: keyorder[i:i] = ['city', 'street'] 

it's probably best to just list all the fields in the correct order:

 class MyForm(ModelForm): class Meta: model=Customer fields=[..., 'name', 'street', 'city', ...] 
+7
source share
 from django import forms class CustomForm(forms.Form): ORDER = ('field1', 'field2', 'field3') def __init__(self, *args, **kwargs): super(CustomForm, self).__init__(*args, **kwargs) fields = OrderedDict() for key in self.ORDER: fields[key] = self.fields.pop(key) self.fields = fields 
+4
source share

In Django 1.9, they add a new argument to the Form class. Now you can change the order by specifying field_order for example, adding two fields to the user's application form:

 class SignupFormExtra(SignupForm): """ A form to demonstrate how to add extra fields to the signup form, in this case adding the first and last name. """ first_name = forms.CharField(label=_(u'First name'), max_length=30, required=False) last_name = forms.CharField(label=_(u'Last name'), max_length=30, required=False) field_order=['first_name','last_name'] 

You can use it in any form inheriting from the Form class.

By default, Form.field_order = None, which preserves 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 indicated in the list, and the remaining fields are added in the default order.

+4
source share

When upgrading to Django 1.7 Skyjur, using .keyOrder stopped working (now Django uses collections.OrderedDict ). As a result, I had to find a job, and this is what seems to work for me:

 from collections import OrderedDict ... class MyForm(forms def __init__(self, *args, **kwargs): fields = OrderedDict() for key in ("my_preferred_first_field", "my_preferred_second_field"): fields[key] = self.fields.pop(key) for key, value in self.fields.items(): fields[key] = value self.fields = fields 
+2
source share

All Articles