Forms, forms, forms
Some questions answered about Django forms.
...again based on questions that keep cropping up in the IRC channels.
1. How do I add or change fields on a ModelForm?
The exact same way you do on a normal Form. If the name of the field matches a field that already exists on the model the form is using, it will override the default.
class Cool(forms.ModelForm): new = forms.CharField() class Meta: model = User
2. If I add fields to a ModelForm, the data in those fields does not get saved.
No, they won't, because they aren't attached to the model, so you would have to save them manually.
3. Can one model form have more than one model?
No.
4. But my form is quite complicated....
Remember the following:
- Django forms are about data validation
- ... they just happen to also render themselves nicely as some HTML
- a ModelForm is a form for one and only one model
- a Form is not bound to a model and can be any number of fields
- a HTML Form can contain any number of Form or ModelForm instance
So for example, if you make a User Profile, you might have one HTML page to edit user details like email address (in the User model) and Facebook account (in the User Profile model). To do this:
- Make two ModelForms, one for each model.
- Pass both through to the view, have both render on the same template.
- The template will look something like this:
<form>
{{ form_one }}
{{ form_two }}
</form>
- When the form is submitted, all you have to do is check the two forms are valid, something like:
if form_one.is_valid() and form_two.is_valid(): form_one.save() form_two.save()
Although the names are similar, a HTML Form and a Django Form are quite different.
Update: Sep 2009, improving some of the grammar and erm words.
Comments
There are 2 comment(s).
http://becomingguru.com/ on Jul, 22You need to inherit
class Cool(forms.ModelForm)than forms.Form Seems like an oversight.
Login to add comments

