About •  Books •  Apps •  Jobs •   Feeds •  Twitter
Login

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:

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:

<form>
{{ form_one }}
{{ form_two }}
</form>
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).

You need to inherit class Cool(forms.ModelForm) than forms.Form Seems like an oversight.

http://becomingguru.com/ on Jul, 22

Thanks, you are right, will fix.

Andy McKay on Jul, 22

Login to add comments