Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django forms set field order

I am trying to set the fieldorder of my form. but somehow it just stays in alphabetical order. Anyone has some suggestions? i tried class Meta: fields = ["field", "field"] and adding a keyOrder in the init

form:

class HangarFilterForm(forms.Form):

    FIELDS = [
        ("", ""),
        ("warp", "Warp"),
        ("cargo_space", "Cargo Space"),
        ("smuggle_bay", "Smuggle Bay"),
        ("dock", "Dock/Undock"),
        ("enter_warp", "Enter Warp"),
        ("fuel_bay", "Fuel Bay"),
        ("fuel_cost", "Fuel Cost"),
    ]

    PER_PAGE = [
        (10, ""),
        (5, "5 ships"),
        (10, "10 ships"),
        (25, "25 ships"),
        (50, "50 ships"),
    ]

    field_1 = forms.ChoiceField(choices=FIELDS, label="1st attribute", required=False)
    field_2 = forms.ChoiceField(choices=FIELDS, label="2nd attribute", required=False)
    per_page = forms.ChoiceField(choices=PER_PAGE, required=False)

    def __init__(self, *args, **kwargs):
        super(HangarFilterForm, self).__init__(*args, **kwargs)
        self.fields['planet'] = forms.ChoiceField(
                        choices=[("", "")] + [ (o.id, o.name) for o in    lanet.objects.all().order_by("name")], 
                        required=False)
        self.fields['type'] = forms.ChoiceField(
                        choices=[("", "")] + [ (o[0], o[1]) for o in ShipTemplate.SHIP_TYPES], required=False)
        self.fields.keyOrder = ["planet", "type", "field_1", "field_2", "per_page"]
like image 536
Hans de Jong Avatar asked Dec 18 '14 20:12

Hans de Jong


People also ask

What is form Is_valid () in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

What does cleaned_data do in Django?

cleaned_data is where all validated fields are stored.

What is CharField in Django?

CharField is a string field, for small- to large-sized strings. It is like a string field in C/C+++. CharField is generally used for storing small strings like first name, last name, etc. To store larger text TextField is used. The default form widget for this field is TextInput.

What is form Is_bound?

is_bound attribute and is_valid() method We can use is_bound attribute to know whether the form is inbound state or not. If the form is in the bound state then the is_bound returns True , otherwise False . Similarly, we can use the is_valid() method to check whether the entered data is valid or not.


2 Answers

In Django 1.9, new way of forcing the order of form's fields has been added : field_order.

Take a look (link to version 1.9): https://docs.djangoproject.com/en/1.9/ref/forms/api/#django.forms.Form.field_order

(and a link to dev version): https://docs.djangoproject.com/en/dev/ref/forms/api/#django.forms.Form.field_order

Find below a short example (using Django 1.9)

models.py:

from django.db import models

class Project(models.Model):
     end_date = models.DateField(verbose_name='End date',
                                blank=True)

    start_date = models.DateField(verbose_name='Start date',
                                  blank=True)

    title = models.CharField(max_length=255,
                             blank=False,
                             verbose_name='Title')

    def __str__(self):
        return self.title

forms.py

from django.forms import ModelForm, DateTimeField, SelectDateWidget

from XXX.models import Project

class ProjectForm(ModelForm):
    class Meta:
        model = Project
        fields = '__all__'

    start_date = DateTimeField(widget=SelectDateWidget)
    end_date = DateTimeField(widget=SelectDateWidget)

    field_order = ['start_date', 'end_date']

In this example the fields will be rearranged to:

  1. start_date <== using the list in the form class
  2. end_date <== using the list in the form class
  3. title <== not mentioned in the list, thus using the default ordering
like image 61
Jack L. Avatar answered Oct 23 '22 22:10

Jack L.


I tried setting fields in Meta part of form in django 2.1 and it also did the trick:

class MyForm(forms.ModelForm):
    ...

    class Meta:
        model = Contact
        fields = ('field_1', 'field_2', 'field_3', 'field_4',)
like image 3
Alex Jolig Avatar answered Oct 23 '22 23:10

Alex Jolig