views:

648

answers:

2

Could anyone please explain to me similarities and differences of Django's forms.Form & forms.ModelForm? I've used Django for 4 days, so excuse me if I don't know basic things. Thanks in advance!

A: 

The similarities are that they both generate sets of form inputs using widgets, and both validate data sent by the browser. The differences are that ModelForm gets its field definition from a specified model class, and also has methods that deal with saving of the underlying model to the database.

Ignacio Vazquez-Abrams
+5  A: 

Forms created from forms.Form are manually configured by you. You're better off using these for forms that do not directly interact with models. For example a contact form, or a newsletter subscription form, where you might not necessarily be interacting with the database.

Where as a form created from forms.ModelForm will be automatically created and then can later be tweaked by you. The best examples really are from the superb documentation provided on the Django website.

forms.Form:
Documentation: Form objects
Example of a normal form created with forms.Form:

from django import forms

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

forms.ModelForm:
Documentation: Creating forms from models
Straight from the docs:

If your form is going to be used to directly add or edit a Django model, you can use a ModelForm to avoid duplicating your model description.

Example of a model form created with forms.Modelform:

from django.forms import ModelForm

# Create the form class.
class ArticleForm(ModelForm):
    class Meta:
        model = Article

This form automatically has all the same field types as the Article model it was created from.

jathanism
Thanks! May I ask: Can I render ModelForm on normal views which are not in admin area? Form can be rendered and processed in normal views when you pass request.POST to initialize it.
Viet
Yep. That is their intended usage. The admin forms are a whole different beast and out of the scope of this question. Get used to referring to the official documentation. It is superb and it will save you almost every time.
jathanism
I'll try. Thank you very much!
Viet