Creating Forms from Models

Let’s build something a little more interesting: a form that submits a new publisher to our book application. An important rule of thumb in software development that Django tries to adhere to is Don’t Repeat Yourself (DRY). Andy Hunt and Dave Thomas in The Pragmatic Programmer define this as follows:

Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

Our Publisher model class says that a publisher has a name, address, city, state_province, country, and website. Duplicating this information in a form definition would break the DRY rule. Instead, we can use a useful shortcut: form_for_model():

from models import Publisher
from django.newforms import form_for_model
PublisherForm = form_for_model(Publisher)

PublisherForm is a Form subclass, just like the ContactForm class we created manually earlier on. We can use it in much the same way:

from forms import PublisherForm
def add_publisher(request):
if request.method == ‘POST’:
form = PublisherForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect(‘/add_publisher/thanks/’)
else:
form = PublisherForm()
return render_to_response(‘books/add_publisher.html’, {‘form’: form})

The add_publisher.html file is almost identical to our original contact.html template, so it has been omitted. Also remember to add a new pattern to the URLconf: (r’^add_publisher/$’, ‘mysite.books.views.add_publisher’).

There’s one more shortcut being demonstrated here. Since forms derived from models are often used to save new instances of the model to the database, the form class created by form_for_model includes a convenient save() method. This deals with the common case; you’re welcome to ignore it if you want to do something a bit more involved with the submitted data.
form_for_instance() is a related method that can create a preinitialized form from an instance of a model class. This is useful for creating “edit” forms.8.

Back to Tutorial

Share this post
[social_warfare]
Configuration for CGI
Proxy Support

Get industry recognized certification – Contact us

keyboard_arrow_up