Consider this example:
from django import newforms as forms
class UserForm(forms.Form):
# Used for registering new accounts.
username = forms.CharField(max_length=20)
email = forms.EmailField()
password = forms.CharField(max_length=20)
password2 = forms.CharField(max_length=20)
# Lots of validators which check if username is unique,
# password1 == password2 and so on.
class UserProfileForm(UserForm):
# Inherits all UserForm fields and validators and adds
# optional profile entries.
first_name = forms.CharField(max_length=30)
last_name = forms.CharField(max_length=30)
jabber_id = forms.EmailField(required=False)
The UserProfileForm can inherit all the goods of UserForm: fields and validators. But the field order may look a bit messy then:
>>> UserProfileForm.base_fields.keys()
['username',
'email',
'password',
'password2',
'first_name',
'last_name',
'jabber_id']
It would be nice to have email grouped with jabber_id, first_name and last_name with username, etc. It's of course possible to do it using custom template, but violates DRY principle and renders as_*() methods useless.
The attached patch allows to specify a custom Field order within a Form, even with inherited fields.
Every Field may have an additional weight parameter with default value of 0. All fields are sorted in ascending weight order.
The example forms customized with weight parameters:
from django import newforms as forms
class UserForm(forms.Form):
username = forms.CharField(max_length=20, weight=-2)
email = forms.EmailField()
password = forms.CharField(max_length=20, weight=1)
password2 = forms.CharField(max_length=20, weight=1)
class UserProfileForm(UserForm):
first_name = forms.CharField(max_length=30, weight=-1)
last_name = forms.CharField(max_length=30, weight=-1)
jabber_id = forms.EmailField()
And the effect:
>>> UserProfileForm.base_fields.keys()
['username',
'first_name',
'last_name',
'email',
'jabber_id',
'password',
'password2']