Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Django Know the Order to Render Form Fields?

If I have a Django form such as:

class ContactForm(forms.Form):     subject = forms.CharField(max_length=100)     message = forms.CharField()     sender = forms.EmailField() 

And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.

My question is how does Django know the order that class variables where defined?

(Also how do I override this order, for example when I want to add a field from the classe's init method?)

like image 739
Greg Avatar asked Dec 08 '08 20:12

Greg


People also ask

How does form Is_valid work in django?

A Form instance has an is_valid() method, which runs validation routines for all its fields. When this method is called, if all fields contain valid data, it will: return True. place the form's data in its cleaned_data attribute.

What is prefix in django forms?

parameter [Django-doc]. This prefix parameter will add a prefix to all the form input items that arise from that form. For example if we specify prefix='father' for the FatherForm , then the name of the items will be father-name , and father-first_name .


2 Answers

New to Django 1.9 is Form.field_order and Form.order_fields().

# forms.Form example class SignupForm(forms.Form):      password = ...     email = ...     username = ...      field_order = ['username', 'email', 'password']   # forms.ModelForm example class UserAccount(forms.ModelForm):      custom_field = models.CharField(max_length=254)      def Meta:         model = User         fields = ('username', 'email')      field_order = ['username', 'custom_field', 'password'] 
like image 101
Steve Tjoa Avatar answered Sep 22 '22 14:09

Steve Tjoa


[NOTE: this answer is now pretty completely outdated - please see the discussion below it, and more recent answers].

If f is a form, its fields are f.fields, which is a django.utils.datastructures.SortedDict (it presents the items in the order they are added). After form construction f.fields has a keyOrder attribute, which is a list containing the field names in the order they should be presented. You can set this to the correct ordering (though you need to exercise care to ensure you don't omit items or add extras).

Here's an example I just created in my current project:

class PrivEdit(ModelForm):     def __init__(self, *args, **kw):         super(ModelForm, self).__init__(*args, **kw)         self.fields.keyOrder = [             'super_user',             'all_districts',             'multi_district',             'all_schools',             'manage_users',             'direct_login',             'student_detail',             'license']     class Meta:         model = Privilege 
like image 30
holdenweb Avatar answered Sep 23 '22 14:09

holdenweb