2005-07-24 19:02:22 +00:00
|
|
|
===============================
|
|
|
|
Forms, fields, and manipulators
|
|
|
|
===============================
|
|
|
|
|
2006-12-15 18:00:50 +00:00
|
|
|
Forwards-compatibility note
|
|
|
|
===========================
|
|
|
|
|
|
|
|
The legacy forms/manipulators system described in this document is going to be
|
|
|
|
replaced in the next Django release. If you're starting from scratch, we
|
|
|
|
strongly encourage you not to waste your time learning this. Instead, learn and
|
|
|
|
use the django.newforms system, which we have begun to document in the
|
|
|
|
`newforms documentation`_.
|
|
|
|
|
|
|
|
If you have legacy form/manipulator code, read the "Migration plan" section in
|
|
|
|
that document to understand how we're making the switch.
|
|
|
|
|
2007-01-24 20:08:47 +00:00
|
|
|
.. _newforms documentation: ../newforms/
|
2006-12-15 18:00:50 +00:00
|
|
|
|
|
|
|
Introduction
|
|
|
|
============
|
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
Once you've got a chance to play with Django's admin interface, you'll probably
|
|
|
|
wonder if the fantastic form validation framework it uses is available to user
|
2005-07-25 17:18:39 +00:00
|
|
|
code. It is, and this document explains how the framework works.
|
2005-07-24 19:02:22 +00:00
|
|
|
|
2005-07-25 17:18:39 +00:00
|
|
|
We'll take a top-down approach to examining Django's form validation framework,
|
2005-08-23 14:31:08 +00:00
|
|
|
because much of the time you won't need to use the lower-level APIs. Throughout
|
2005-07-24 19:02:22 +00:00
|
|
|
this document, we'll be working with the following model, a "place" object::
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2006-06-14 03:31:34 +00:00
|
|
|
from django.db import models
|
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
PLACE_TYPES = (
|
|
|
|
(1, 'Bar'),
|
|
|
|
(2, 'Restaurant'),
|
|
|
|
(3, 'Movie Theater'),
|
|
|
|
(4, 'Secret Hideout'),
|
|
|
|
)
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2006-06-14 03:31:34 +00:00
|
|
|
class Place(models.Model):
|
|
|
|
name = models.CharField(maxlength=100)
|
|
|
|
address = models.CharField(maxlength=100, blank=True)
|
|
|
|
city = models.CharField(maxlength=50, blank=True)
|
|
|
|
state = models.USStateField()
|
|
|
|
zip_code = models.CharField(maxlength=5, blank=True)
|
|
|
|
place_type = models.IntegerField(choices=PLACE_TYPES)
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
class Admin:
|
|
|
|
pass
|
|
|
|
|
|
|
|
def __str__(self):
|
2005-07-24 19:02:22 +00:00
|
|
|
return self.name
|
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
Defining the above class is enough to create an admin interface to a ``Place``,
|
2005-07-24 19:02:22 +00:00
|
|
|
but what if you want to allow public users to submit places?
|
|
|
|
|
2006-12-15 18:00:50 +00:00
|
|
|
Automatic Manipulators
|
|
|
|
======================
|
2005-07-24 19:02:22 +00:00
|
|
|
|
|
|
|
The highest-level interface for object creation and modification is the
|
2006-12-15 18:00:50 +00:00
|
|
|
**automatic Manipulator** framework. An automatic manipulator is a utility
|
|
|
|
class tied to a given model that "knows" how to create or modify instances of
|
|
|
|
that model and how to validate data for the object. Automatic Manipulators come
|
|
|
|
in two flavors: ``AddManipulators`` and ``ChangeManipulators``. Functionally
|
|
|
|
they are quite similar, but the former knows how to create new instances of the
|
|
|
|
model, while the latter modifies existing instances. Both types of classes are
|
|
|
|
automatically created when you define a new class::
|
2005-07-24 19:02:22 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
>>> from mysite.myapp.models import Place
|
|
|
|
>>> Place.AddManipulator
|
|
|
|
<class 'django.models.manipulators.AddManipulator'>
|
|
|
|
>>> Place.ChangeManipulator
|
|
|
|
<class 'django.models.manipulators.ChangeManipulator'>
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
Using the ``AddManipulator``
|
|
|
|
----------------------------
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
We'll start with the ``AddManipulator``. Here's a very simple view that takes
|
|
|
|
POSTed data from the browser and creates a new ``Place`` object::
|
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
from django.shortcuts import render_to_response
|
|
|
|
from django.http import Http404, HttpResponse, HttpResponseRedirect
|
|
|
|
from django import forms
|
|
|
|
from mysite.myapp.models import Place
|
2005-07-24 19:02:22 +00:00
|
|
|
|
|
|
|
def naive_create_place(request):
|
|
|
|
"""A naive approach to creating places; don't actually use this!"""
|
2005-07-25 17:18:39 +00:00
|
|
|
# Create the AddManipulator.
|
2006-05-02 01:31:56 +00:00
|
|
|
manipulator = Place.AddManipulator()
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
# Make a copy of the POSTed data so that do_html2python can
|
2005-07-25 17:18:39 +00:00
|
|
|
# modify it in place (request.POST is immutable).
|
2005-07-24 19:02:22 +00:00
|
|
|
new_data = request.POST.copy()
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
# Convert the request data (which will all be strings) into the
|
2005-07-25 17:18:39 +00:00
|
|
|
# appropriate Python types for those fields.
|
2005-07-24 19:02:22 +00:00
|
|
|
manipulator.do_html2python(new_data)
|
2005-07-25 17:18:39 +00:00
|
|
|
|
|
|
|
# Save the new object.
|
2005-07-24 19:02:22 +00:00
|
|
|
new_place = manipulator.save(new_data)
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
# It worked!
|
|
|
|
return HttpResponse("Place created: %s" % new_place)
|
|
|
|
|
2005-07-25 17:18:39 +00:00
|
|
|
The ``naive_create_place`` example works, but as you probably can tell, this
|
|
|
|
view has a number of problems:
|
2005-07-24 19:02:22 +00:00
|
|
|
|
2005-07-25 17:18:39 +00:00
|
|
|
* No validation of any sort is performed. If, for example, the ``name`` field
|
2005-07-24 19:02:22 +00:00
|
|
|
isn't given in ``request.POST``, the save step will cause a database error
|
2005-07-25 17:18:39 +00:00
|
|
|
because that field is required. Ugly.
|
|
|
|
|
|
|
|
* Even if you *do* perform validation, there's still no way to give that
|
2006-01-13 15:01:16 +00:00
|
|
|
information to the user in any sort of useful way.
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-11-22 14:24:07 +00:00
|
|
|
* You'll have to separately create a form (and view) that submits to this
|
2005-07-25 17:18:39 +00:00
|
|
|
page, which is a pain and is redundant.
|
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
Let's dodge these problems momentarily to take a look at how you could create a
|
|
|
|
view with a form that submits to this flawed creation view::
|
|
|
|
|
|
|
|
def naive_create_place_form(request):
|
|
|
|
"""Simplistic place form view; don't actually use anything like this!"""
|
2005-07-25 17:18:39 +00:00
|
|
|
# Create a FormWrapper object that the template can use. Ignore
|
|
|
|
# the last two arguments to FormWrapper for now.
|
2006-05-02 01:31:56 +00:00
|
|
|
form = forms.FormWrapper(Place.AddManipulator(), {}, {})
|
|
|
|
return render_to_response('places/naive_create_form.html', {'form': form})
|
2005-07-24 19:02:22 +00:00
|
|
|
|
2005-07-25 17:18:39 +00:00
|
|
|
(This view, as well as all the following ones, has the same imports as in the
|
|
|
|
first example above.)
|
2005-07-24 19:02:22 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
The ``forms.FormWrapper`` object is a wrapper that templates can
|
|
|
|
easily deal with to create forms. Here's the ``naive_create_form.html``
|
|
|
|
template::
|
2005-07-24 19:02:22 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
{% extends "base.html" %}
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
{% block content %}
|
|
|
|
<h1>Create a place:</h1>
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
<form method="post" action="../do_new/">
|
|
|
|
<p><label for="id_name">Name:</label> {{ form.name }}</p>
|
|
|
|
<p><label for="id_address">Address:</label> {{ form.address }}</p>
|
|
|
|
<p><label for="id_city">City:</label> {{ form.city }}</p>
|
|
|
|
<p><label for="id_state">State:</label> {{ form.state }}</p>
|
|
|
|
<p><label for="id_zip_code">Zip:</label> {{ form.zip_code }}</p>
|
|
|
|
<p><label for="id_place_type">Place type:</label> {{ form.place_type }}</p>
|
|
|
|
<input type="submit" />
|
|
|
|
</form>
|
|
|
|
{% endblock %}
|
2005-07-25 17:18:39 +00:00
|
|
|
|
|
|
|
Before we get back to the problems with these naive set of views, let's go over
|
2006-09-21 13:30:01 +00:00
|
|
|
some salient points of the above template:
|
2005-07-24 19:02:22 +00:00
|
|
|
|
|
|
|
* Field "widgets" are handled for you: ``{{ form.field }}`` automatically
|
|
|
|
creates the "right" type of widget for the form, as you can see with the
|
|
|
|
``place_type`` field above.
|
2005-07-25 17:18:39 +00:00
|
|
|
|
|
|
|
* There isn't a way just to spit out the form. You'll still need to define
|
|
|
|
how the form gets laid out. This is a feature: Every form should be
|
|
|
|
designed differently. Django doesn't force you into any type of mold.
|
|
|
|
If you must use tables, use tables. If you're a semantic purist, you can
|
|
|
|
probably find better HTML than in the above template.
|
|
|
|
|
2006-09-21 13:30:01 +00:00
|
|
|
* To avoid name conflicts, the ``id`` values of form elements take the
|
|
|
|
form "id_*fieldname*".
|
2005-07-25 17:18:39 +00:00
|
|
|
|
|
|
|
By creating a creation form we've solved problem number 3 above, but we still
|
|
|
|
don't have any validation. Let's revise the validation issue by writing a new
|
|
|
|
creation view that takes validation into account::
|
2005-07-24 19:02:22 +00:00
|
|
|
|
|
|
|
def create_place_with_validation(request):
|
2006-05-02 01:31:56 +00:00
|
|
|
manipulator = Place.AddManipulator()
|
2005-07-24 19:02:22 +00:00
|
|
|
new_data = request.POST.copy()
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
# Check for validation errors
|
|
|
|
errors = manipulator.get_validation_errors(new_data)
|
2007-02-13 05:02:47 +00:00
|
|
|
manipulator.do_html2python(new_data)
|
2005-07-24 19:02:22 +00:00
|
|
|
if errors:
|
2006-05-02 01:31:56 +00:00
|
|
|
return render_to_response('places/errors.html', {'errors': errors})
|
2005-07-24 19:02:22 +00:00
|
|
|
else:
|
2006-05-02 01:31:56 +00:00
|
|
|
new_place = manipulator.save(new_data)
|
2005-07-24 19:02:22 +00:00
|
|
|
return HttpResponse("Place created: %s" % new_place)
|
|
|
|
|
|
|
|
In this new version, errors will be found -- ``manipulator.get_validation_errors``
|
|
|
|
handles all the validation for you -- and those errors can be nicely presented
|
|
|
|
on an error page (templated, of course)::
|
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
{% extends "base.html" %}
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
{% block content %}
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
<h1>Please go back and correct the following error{{ errors|pluralize }}:</h1>
|
|
|
|
<ul>
|
|
|
|
{% for e in errors.items %}
|
|
|
|
<li>Field "{{ e.0 }}": {{ e.1|join:", " }}</li>
|
|
|
|
{% endfor %}
|
|
|
|
</ul>
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
{% endblock %}
|
|
|
|
|
2005-07-25 17:18:39 +00:00
|
|
|
Still, this has its own problems:
|
2005-07-24 19:02:22 +00:00
|
|
|
|
2005-07-25 17:18:39 +00:00
|
|
|
* There's still the issue of creating a separate (redundant) view for the
|
2005-07-24 19:02:22 +00:00
|
|
|
submission form.
|
|
|
|
|
2005-07-25 17:18:39 +00:00
|
|
|
* Errors, though nicely presented, are on a separate page, so the user will
|
|
|
|
have to use the "back" button to fix errors. That's ridiculous and unusable.
|
|
|
|
|
|
|
|
The best way to deal with these issues is to collapse the two views -- the form
|
|
|
|
and the submission -- into a single view. This view will be responsible for
|
|
|
|
creating the form, validating POSTed data, and creating the new object (if the
|
|
|
|
data is valid). An added bonus of this approach is that errors and the form will
|
|
|
|
both be available on the same page, so errors with fields can be presented in
|
|
|
|
context.
|
2005-07-24 19:02:22 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
.. admonition:: Philosophy:
|
2005-07-24 19:02:22 +00:00
|
|
|
|
|
|
|
Finally, for the HTTP purists in the audience (and the authorship), this
|
2005-07-25 17:18:39 +00:00
|
|
|
nicely matches the "true" meanings of HTTP GET and HTTP POST: GET fetches
|
|
|
|
the form, and POST creates the new object.
|
2005-07-24 19:02:22 +00:00
|
|
|
|
|
|
|
Below is the finished view::
|
|
|
|
|
|
|
|
def create_place(request):
|
2006-05-02 01:31:56 +00:00
|
|
|
manipulator = Place.AddManipulator()
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2006-10-23 07:51:29 +00:00
|
|
|
if request.method == 'POST':
|
2005-07-25 17:18:39 +00:00
|
|
|
# If data was POSTed, we're trying to create a new Place.
|
2005-07-24 19:02:22 +00:00
|
|
|
new_data = request.POST.copy()
|
2005-07-25 17:18:39 +00:00
|
|
|
|
|
|
|
# Check for errors.
|
2005-07-24 19:02:22 +00:00
|
|
|
errors = manipulator.get_validation_errors(new_data)
|
2007-02-13 05:02:47 +00:00
|
|
|
manipulator.do_html2python(new_data)
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
if not errors:
|
2005-07-25 17:18:39 +00:00
|
|
|
# No errors. This means we can save the data!
|
2005-07-24 19:02:22 +00:00
|
|
|
new_place = manipulator.save(new_data)
|
2005-07-25 17:18:39 +00:00
|
|
|
|
|
|
|
# Redirect to the object's "edit" page. Always use a redirect
|
|
|
|
# after POST data, so that reloads don't accidently create
|
|
|
|
# duplicate entires, and so users don't see the confusing
|
|
|
|
# "Repost POST data?" alert box in their browsers.
|
2005-07-24 19:02:22 +00:00
|
|
|
return HttpResponseRedirect("/places/edit/%i/" % new_place.id)
|
|
|
|
else:
|
2005-07-25 17:18:39 +00:00
|
|
|
# No POST, so we want a brand new form without any data or errors.
|
2005-07-24 19:02:22 +00:00
|
|
|
errors = new_data = {}
|
2005-07-25 17:18:39 +00:00
|
|
|
|
|
|
|
# Create the FormWrapper, template, context, response.
|
2006-05-02 01:31:56 +00:00
|
|
|
form = forms.FormWrapper(manipulator, new_data, errors)
|
|
|
|
return render_to_response('places/create_form.html', {'form': form})
|
2005-07-24 19:02:22 +00:00
|
|
|
|
|
|
|
and here's the ``create_form`` template::
|
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
{% extends "base.html" %}
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
{% block content %}
|
|
|
|
<h1>Create a place:</h1>
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
{% if form.has_errors %}
|
2006-05-02 01:31:56 +00:00
|
|
|
<h2>Please correct the following error{{ form.error_dict|pluralize }}:</h2>
|
2005-07-24 19:02:22 +00:00
|
|
|
{% endif %}
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
<form method="post" action=".">
|
|
|
|
<p>
|
2005-07-25 17:18:39 +00:00
|
|
|
<label for="id_name">Name:</label> {{ form.name }}
|
2005-07-24 19:02:22 +00:00
|
|
|
{% if form.name.errors %}*** {{ form.name.errors|join:", " }}{% endif %}
|
|
|
|
</p>
|
|
|
|
<p>
|
|
|
|
<label for="id_address">Address:</label> {{ form.address }}
|
|
|
|
{% if form.address.errors %}*** {{ form.address.errors|join:", " }}{% endif %}
|
|
|
|
</p>
|
|
|
|
<p>
|
|
|
|
<label for="id_city">City:</label> {{ form.city }}
|
|
|
|
{% if form.city.errors %}*** {{ form.city.errors|join:", " }}{% endif %}
|
|
|
|
</p>
|
|
|
|
<p>
|
|
|
|
<label for="id_state">State:</label> {{ form.state }}
|
|
|
|
{% if form.state.errors %}*** {{ form.state.errors|join:", " }}{% endif %}
|
|
|
|
</p>
|
|
|
|
<p>
|
|
|
|
<label for="id_zip_code">Zip:</label> {{ form.zip_code }}
|
|
|
|
{% if form.zip_code.errors %}*** {{ form.zip_code.errors|join:", " }}{% endif %}
|
|
|
|
</p>
|
|
|
|
<p>
|
|
|
|
<label for="id_place_type">Place type:</label> {{ form.place_type }}
|
|
|
|
{% if form.place_type.errors %}*** {{ form.place_type.errors|join:", " }}{% endif %}
|
|
|
|
</p>
|
|
|
|
<input type="submit" />
|
|
|
|
</form>
|
|
|
|
{% endblock %}
|
|
|
|
|
|
|
|
The second two arguments to ``FormWrapper`` (``new_data`` and ``errors``)
|
|
|
|
deserve some mention.
|
|
|
|
|
2005-07-25 17:18:39 +00:00
|
|
|
The first is any "default" data to be used as values for the fields. Pulling
|
|
|
|
the data from ``request.POST``, as is done above, makes sure that if there are
|
|
|
|
errors, the values the user put in aren't lost. If you try the above example,
|
|
|
|
you'll see this in action.
|
2005-07-24 19:02:22 +00:00
|
|
|
|
|
|
|
The second argument is the error list retrieved from
|
2005-07-25 17:18:39 +00:00
|
|
|
``manipulator.get_validation_errors``. When passed into the ``FormWrapper``,
|
|
|
|
this gives each field an ``errors`` item (which is a list of error messages
|
|
|
|
associated with the field) as well as a ``html_error_list`` item, which is a
|
|
|
|
``<ul>`` of error messages. The above template uses these error items to
|
2006-05-02 01:31:56 +00:00
|
|
|
display a simple error message next to each field. The error list is saved as
|
|
|
|
an ``error_dict`` attribute of the ``FormWrapper`` object.
|
2005-07-24 19:02:22 +00:00
|
|
|
|
|
|
|
Using the ``ChangeManipulator``
|
|
|
|
-------------------------------
|
|
|
|
|
2005-07-25 17:18:39 +00:00
|
|
|
The above has covered using the ``AddManipulator`` to create a new object. What
|
|
|
|
about editing an existing one? It's shockingly similar to creating a new one::
|
2005-07-24 19:02:22 +00:00
|
|
|
|
|
|
|
def edit_place(request, place_id):
|
2005-07-25 17:18:39 +00:00
|
|
|
# Get the place in question from the database and create a
|
|
|
|
# ChangeManipulator at the same time.
|
2005-07-24 19:02:22 +00:00
|
|
|
try:
|
2006-05-02 01:31:56 +00:00
|
|
|
manipulator = Place.ChangeManipulator(place_id)
|
|
|
|
except Place.DoesNotExist:
|
2005-07-24 19:02:22 +00:00
|
|
|
raise Http404
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-11-22 14:24:07 +00:00
|
|
|
# Grab the Place object in question for future use.
|
2005-07-24 19:02:22 +00:00
|
|
|
place = manipulator.original_object
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2006-10-23 07:51:29 +00:00
|
|
|
if request.method == 'POST':
|
2005-07-24 19:02:22 +00:00
|
|
|
new_data = request.POST.copy()
|
|
|
|
errors = manipulator.get_validation_errors(new_data)
|
2007-02-13 05:02:47 +00:00
|
|
|
manipulator.do_html2python(new_data)
|
2005-07-24 19:02:22 +00:00
|
|
|
if not errors:
|
|
|
|
manipulator.save(new_data)
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
# Do a post-after-redirect so that reload works, etc.
|
|
|
|
return HttpResponseRedirect("/places/edit/%i/" % place.id)
|
|
|
|
else:
|
|
|
|
errors = {}
|
|
|
|
# This makes sure the form accurate represents the fields of the place.
|
2006-09-14 13:31:50 +00:00
|
|
|
new_data = manipulator.flatten_data()
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
form = forms.FormWrapper(manipulator, new_data, errors)
|
|
|
|
return render_to_response('places/edit_form.html', {'form': form, 'place': place})
|
2005-07-25 17:18:39 +00:00
|
|
|
|
|
|
|
The only real differences are:
|
|
|
|
|
|
|
|
* We create a ``ChangeManipulator`` instead of an ``AddManipulator``.
|
|
|
|
The argument to a ``ChangeManipulator`` is the ID of the object
|
|
|
|
to be changed. As you can see, the initializer will raise an
|
|
|
|
``ObjectDoesNotExist`` exception if the ID is invalid.
|
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
* ``ChangeManipulator.original_object`` stores the instance of the
|
|
|
|
object being edited.
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2006-09-14 13:31:50 +00:00
|
|
|
* We set ``new_data`` based upon ``flatten_data()`` from the manipulator.
|
2006-09-25 17:42:19 +00:00
|
|
|
``flatten_data()`` takes the data from the original object under
|
|
|
|
manipulation, and converts it into a data dictionary that can be used
|
2006-09-14 13:31:50 +00:00
|
|
|
to populate form elements with the existing values for the object.
|
2005-07-25 17:18:39 +00:00
|
|
|
|
|
|
|
* The above example uses a different template, so create and edit can be
|
|
|
|
"skinned" differently if needed, but the form chunk itself is completely
|
|
|
|
identical to the one in the create form above.
|
|
|
|
|
|
|
|
The astute programmer will notice the add and create functions are nearly
|
|
|
|
identical and could in fact be collapsed into a single view. This is left as an
|
|
|
|
exercise for said programmer.
|
2005-07-24 19:02:22 +00:00
|
|
|
|
|
|
|
(However, the even-more-astute programmer will take heed of the note at the top
|
|
|
|
of this document and check out the `generic views`_ documentation if all she
|
2005-07-25 17:18:39 +00:00
|
|
|
wishes to do is this type of simple create/update.)
|
2005-07-24 19:02:22 +00:00
|
|
|
|
|
|
|
Custom forms and manipulators
|
|
|
|
=============================
|
|
|
|
|
2005-07-25 17:18:39 +00:00
|
|
|
All the above is fine and dandy if you just want to use the automatically
|
|
|
|
created manipulators. But the coolness doesn't end there: You can easily create
|
|
|
|
your own custom manipulators for handling custom forms.
|
2005-07-24 19:02:22 +00:00
|
|
|
|
2005-07-25 17:18:39 +00:00
|
|
|
Custom manipulators are pretty simple. Here's a manipulator that you might use
|
2005-07-24 19:02:22 +00:00
|
|
|
for a "contact" form on a website::
|
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
from django import forms
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
urgency_choices = (
|
|
|
|
(1, "Extremely urgent"),
|
|
|
|
(2, "Urgent"),
|
|
|
|
(3, "Normal"),
|
|
|
|
(4, "Unimportant"),
|
|
|
|
)
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
class ContactManipulator(forms.Manipulator):
|
2005-07-24 19:02:22 +00:00
|
|
|
def __init__(self):
|
|
|
|
self.fields = (
|
2006-05-02 01:31:56 +00:00
|
|
|
forms.EmailField(field_name="from", is_required=True),
|
|
|
|
forms.TextField(field_name="subject", length=30, maxlength=200, is_required=True),
|
|
|
|
forms.SelectField(field_name="urgency", choices=urgency_choices),
|
|
|
|
forms.LargeTextField(field_name="contents", is_required=True),
|
2005-07-24 19:02:22 +00:00
|
|
|
)
|
2005-07-25 17:18:39 +00:00
|
|
|
|
|
|
|
A certain similarity to Django's models should be apparent. The only required
|
2005-07-24 19:02:22 +00:00
|
|
|
method of a custom manipulator is ``__init__`` which must define the fields
|
2006-05-02 01:31:56 +00:00
|
|
|
present in the manipulator. See the ``django.forms`` module for
|
2005-07-24 19:02:22 +00:00
|
|
|
all the form fields provided by Django.
|
|
|
|
|
2005-07-25 17:18:39 +00:00
|
|
|
You use this custom manipulator exactly as you would use an auto-generated one.
|
|
|
|
Here's a simple function that might drive the above form::
|
2005-07-24 19:02:22 +00:00
|
|
|
|
|
|
|
def contact_form(request):
|
2005-11-16 03:37:01 +00:00
|
|
|
manipulator = ContactManipulator()
|
2006-10-23 07:51:29 +00:00
|
|
|
if request.method == 'POST':
|
2005-07-24 19:02:22 +00:00
|
|
|
new_data = request.POST.copy()
|
|
|
|
errors = manipulator.get_validation_errors(new_data)
|
2007-02-13 05:02:47 +00:00
|
|
|
manipulator.do_html2python(new_data)
|
2005-07-24 19:02:22 +00:00
|
|
|
if not errors:
|
2005-07-25 17:18:39 +00:00
|
|
|
|
|
|
|
# Send e-mail using new_data here...
|
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
return HttpResponseRedirect("/contact/thankyou/")
|
|
|
|
else:
|
|
|
|
errors = new_data = {}
|
2006-05-02 01:31:56 +00:00
|
|
|
form = forms.FormWrapper(manipulator, new_data, errors)
|
|
|
|
return render_to_response('contact_form.html', {'form': form})
|
2006-09-25 17:42:19 +00:00
|
|
|
|
2006-07-28 02:42:44 +00:00
|
|
|
``FileField`` and ``ImageField`` special cases
|
|
|
|
==============================================
|
2006-07-27 23:59:35 +00:00
|
|
|
|
2006-07-28 02:42:44 +00:00
|
|
|
Dealing with ``FileField`` and ``ImageField`` objects is a little more
|
2006-07-27 23:59:35 +00:00
|
|
|
complicated.
|
|
|
|
|
|
|
|
First, you'll need to make sure that your ``<form>`` element correctly defines
|
2006-07-28 02:30:36 +00:00
|
|
|
the ``enctype`` as ``"multipart/form-data"``, in order to upload files::
|
2006-07-27 23:59:35 +00:00
|
|
|
|
2006-07-28 02:30:36 +00:00
|
|
|
<form enctype="multipart/form-data" method="post" action="/foo/">
|
2006-07-27 23:59:35 +00:00
|
|
|
|
2006-07-28 02:30:36 +00:00
|
|
|
Next, you'll need to treat the field in the template slightly differently. A
|
|
|
|
``FileField`` or ``ImageField`` is represented by *two* HTML form elements.
|
|
|
|
|
|
|
|
For example, given this field in a model::
|
2006-07-27 23:59:35 +00:00
|
|
|
|
|
|
|
photo = model.ImageField('/path/to/upload/location')
|
|
|
|
|
2006-07-28 02:30:36 +00:00
|
|
|
You'd need to display two formfields in the template::
|
2006-07-27 23:59:35 +00:00
|
|
|
|
|
|
|
<p><label for="id_photo">Photo:</label> {{ form.photo }}{{ form.photo_file }}</p>
|
|
|
|
|
|
|
|
The first bit (``{{ form.photo }}``) displays the currently-selected file,
|
|
|
|
while the second (``{{ form.photo_file }}``) actually contains the file upload
|
|
|
|
form field. Thus, at the validation layer you need to check the ``photo_file``
|
|
|
|
key.
|
|
|
|
|
2006-07-28 02:30:36 +00:00
|
|
|
Finally, in your view, make sure to access ``request.FILES``, rather than
|
|
|
|
``request.POST``, for the uploaded files. This is necessary because
|
|
|
|
``request.POST`` does not contain file-upload data.
|
|
|
|
|
|
|
|
For example, following the ``new_data`` convention, you might do something like
|
|
|
|
this::
|
2006-07-27 23:59:35 +00:00
|
|
|
|
|
|
|
new_data = request.POST.copy()
|
|
|
|
new_data.update(request.FILES)
|
2005-07-24 19:02:22 +00:00
|
|
|
|
|
|
|
Validators
|
|
|
|
==========
|
|
|
|
|
2005-07-25 17:18:39 +00:00
|
|
|
One useful feature of manipulators is the automatic validation. Validation is
|
|
|
|
done using a simple validation API: A validator is a callable that raises a
|
|
|
|
``ValidationError`` if there's something wrong with the data.
|
2006-05-02 01:31:56 +00:00
|
|
|
``django.core.validators`` defines a host of validator functions (see below),
|
|
|
|
but defining your own couldn't be easier::
|
2005-07-24 19:02:22 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
from django.core import validators
|
|
|
|
from django import forms
|
2005-07-24 19:02:22 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
class ContactManipulator(forms.Manipulator):
|
2005-07-24 19:02:22 +00:00
|
|
|
def __init__(self):
|
|
|
|
self.fields = (
|
|
|
|
# ... snip fields as above ...
|
2006-05-02 01:31:56 +00:00
|
|
|
forms.EmailField(field_name="to", validator_list=[self.isValidToAddress])
|
2005-07-24 19:02:22 +00:00
|
|
|
)
|
2005-07-25 17:18:39 +00:00
|
|
|
|
2005-07-24 19:02:22 +00:00
|
|
|
def isValidToAddress(self, field_data, all_data):
|
|
|
|
if not field_data.endswith("@example.com"):
|
2005-12-24 16:27:53 +00:00
|
|
|
raise validators.ValidationError("You can only send messages to example.com e-mail addresses.")
|
2005-07-25 17:18:39 +00:00
|
|
|
|
|
|
|
Above, we've added a "to" field to the contact form, but required that the "to"
|
|
|
|
address end with "@example.com" by adding the ``isValidToAddress`` validator to
|
|
|
|
the field's ``validator_list``.
|
2005-07-24 19:02:22 +00:00
|
|
|
|
|
|
|
The arguments to a validator function take a little explanation. ``field_data``
|
2005-07-25 17:18:39 +00:00
|
|
|
is the value of the field in question, and ``all_data`` is a dictionary of all
|
2006-05-02 01:31:56 +00:00
|
|
|
the data being validated.
|
|
|
|
|
|
|
|
.. admonition:: Note::
|
|
|
|
|
|
|
|
At the point validators are called all data will still be
|
|
|
|
strings (as ``do_html2python`` hasn't been called yet).
|
2005-07-25 17:18:39 +00:00
|
|
|
|
|
|
|
Also, because consistency in user interfaces is important, we strongly urge you
|
|
|
|
to put punctuation at the end of your validation messages.
|
2005-07-24 19:02:22 +00:00
|
|
|
|
2006-09-25 17:42:19 +00:00
|
|
|
When are validators called?
|
2006-09-22 12:46:35 +00:00
|
|
|
---------------------------
|
|
|
|
|
|
|
|
After a form has been submitted, Django first checks to see that all the
|
|
|
|
required fields are present and non-empty. For each field that passes that
|
|
|
|
test *and if the form submission contained data* for that field, all the
|
2006-09-25 17:42:19 +00:00
|
|
|
validators for that field are called in turn. The emphasized portion in the
|
2006-09-22 12:46:35 +00:00
|
|
|
last sentence is important: if a form field is not submitted (because it
|
2006-09-29 02:30:42 +00:00
|
|
|
contains no data -- which is normal HTML behavior), the validators are not
|
2006-09-22 12:46:35 +00:00
|
|
|
run against the field.
|
|
|
|
|
|
|
|
This feature is particularly important for models using
|
|
|
|
``models.BooleanField`` or custom manipulators using things like
|
|
|
|
``forms.CheckBoxField``. If the checkbox is not selected, it will not
|
|
|
|
contribute to the form submission.
|
|
|
|
|
2006-09-25 17:42:19 +00:00
|
|
|
If you would like your validator to run *always*, regardless of whether its
|
|
|
|
attached field contains any data, set the ``always_test`` attribute on the
|
|
|
|
validator function. For example::
|
2006-09-22 12:46:35 +00:00
|
|
|
|
|
|
|
def my_custom_validator(field_data, all_data):
|
|
|
|
# ...
|
|
|
|
my_custom_validator.always_test = True
|
|
|
|
|
|
|
|
This validator will always be executed for any field it is attached to.
|
|
|
|
|
2006-09-25 17:43:13 +00:00
|
|
|
Ready-made validators
|
2006-05-02 01:31:56 +00:00
|
|
|
---------------------
|
|
|
|
|
|
|
|
Writing your own validator is not difficult, but there are some situations
|
|
|
|
that come up over and over again. Django comes with a number of validators
|
|
|
|
that can be used directly in your code. All of these functions and classes
|
|
|
|
reside in ``django/core/validators.py``.
|
|
|
|
|
|
|
|
The following validators should all be self-explanatory. Each one provides a
|
|
|
|
check for the given property:
|
|
|
|
|
|
|
|
* isAlphaNumeric
|
|
|
|
* isAlphaNumericURL
|
|
|
|
* isSlug
|
|
|
|
* isLowerCase
|
|
|
|
* isUpperCase
|
|
|
|
* isCommaSeparatedIntegerList
|
|
|
|
* isCommaSeparatedEmailList
|
|
|
|
* isValidIPAddress4
|
|
|
|
* isNotEmpty
|
|
|
|
* isOnlyDigits
|
|
|
|
* isNotOnlyDigits
|
|
|
|
* isInteger
|
|
|
|
* isOnlyLetters
|
|
|
|
* isValidANSIDate
|
|
|
|
* isValidANSITime
|
|
|
|
* isValidEmail
|
|
|
|
* isValidImage
|
|
|
|
* isValidImageURL
|
|
|
|
* isValidPhone
|
|
|
|
* isValidQuicktimeVideoURL
|
|
|
|
* isValidURL
|
|
|
|
* isValidHTML
|
|
|
|
* isWellFormedXml
|
|
|
|
* isWellFormedXmlFragment
|
|
|
|
* isExistingURL
|
|
|
|
* isValidUSState
|
|
|
|
* hasNoProfanities
|
|
|
|
|
|
|
|
There are also a group of validators that are slightly more flexible. For
|
|
|
|
these validators, you create a validator instance, passing in the parameters
|
|
|
|
described below. The returned object is a callable that can be used as a
|
|
|
|
validator.
|
|
|
|
|
|
|
|
For example::
|
|
|
|
|
|
|
|
from django.core import validators
|
|
|
|
from django import forms
|
|
|
|
|
|
|
|
power_validator = validators.IsAPowerOf(2)
|
|
|
|
|
|
|
|
class InstallationManipulator(forms.Manipulator)
|
|
|
|
def __init__(self):
|
|
|
|
self.fields = (
|
|
|
|
...
|
|
|
|
forms.IntegerField(field_name = "size", validator_list=[power_validator])
|
|
|
|
)
|
|
|
|
|
|
|
|
Here, ``validators.IsAPowerOf(...)`` returned something that could be used as
|
|
|
|
a validator (in this case, a check that a number was a power of 2).
|
|
|
|
|
|
|
|
Each of the standard validators that take parameters have an optional final
|
|
|
|
argument (``error_message``) that is the message returned when validation
|
|
|
|
fails. If no message is passed in, a default message is used.
|
|
|
|
|
|
|
|
``AlwaysMatchesOtherField``
|
|
|
|
Takes a field name and the current field is valid if and only if its value
|
|
|
|
matches the contents of the other field.
|
|
|
|
|
|
|
|
``ValidateIfOtherFieldEquals``
|
|
|
|
Takes three parameters: ``other_field``, ``other_value`` and
|
|
|
|
``validator_list``, in that order. If ``other_field`` has a value of
|
2006-10-23 07:59:30 +00:00
|
|
|
``other_value``, then the validators in ``validator_list`` are all run
|
2006-05-02 01:31:56 +00:00
|
|
|
against the current field.
|
|
|
|
|
|
|
|
``RequiredIfOtherFieldNotGiven``
|
|
|
|
Takes the name of the other field and this field is only required if the
|
|
|
|
other field has no value.
|
|
|
|
|
|
|
|
``RequiredIfOtherFieldsNotGiven``
|
|
|
|
Similar to ``RequiredIfOtherFieldNotGiven``, except that it takes a list
|
|
|
|
of field names and if any one of the supplied fields does not have a value
|
|
|
|
provided, the field being validated is required.
|
|
|
|
|
|
|
|
``RequiredIfOtherFieldEquals`` and ``RequiredIfOtherFieldDoesNotEqual``
|
|
|
|
Each of these validator classes takes a field name and a value (in that
|
|
|
|
order). If the given field does (or does not have, in the latter case) the
|
|
|
|
given value, then the current field being validated is required.
|
|
|
|
|
2007-02-25 17:16:38 +00:00
|
|
|
An optional ``other_label`` argument can be passed which, if given, is used
|
|
|
|
in error messages instead of the value. This allows more user friendly error
|
|
|
|
messages if the value itself is not descriptive enough.
|
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
Note that because validators are called before any ``do_html2python()``
|
|
|
|
functions, the value being compared against is a string. So
|
|
|
|
``RequiredIfOtherFieldEquals('choice', '1')`` is correct, whilst
|
|
|
|
``RequiredIfOtherFieldEquals('choice', 1)`` will never result in the
|
|
|
|
equality test succeeding.
|
|
|
|
|
|
|
|
``IsLessThanOtherField``
|
|
|
|
Takes a field name and validates that the current field being validated
|
|
|
|
has a value that is less than (or equal to) the other field's value.
|
|
|
|
Again, comparisons are done using strings, so be cautious about using
|
|
|
|
this function to compare data that should be treated as another type. The
|
|
|
|
string "123" is less than the string "2", for example. If you don't want
|
|
|
|
string comparison here, you will need to write your own validator.
|
|
|
|
|
2006-11-07 04:29:07 +00:00
|
|
|
``NumberIsInRange``
|
2006-11-07 19:07:27 +00:00
|
|
|
Takes two boundary numbers, ``lower`` and ``upper``, and checks that the
|
2006-11-07 04:29:07 +00:00
|
|
|
field is greater than ``lower`` (if given) and less than ``upper`` (if
|
|
|
|
given).
|
|
|
|
|
2006-11-07 19:07:27 +00:00
|
|
|
Both checks are inclusive. That is, ``NumberIsInRange(10, 20)`` will allow
|
|
|
|
values of both 10 and 20. This validator only checks numeric values
|
|
|
|
(e.g., float and integer values).
|
2006-11-07 04:29:07 +00:00
|
|
|
|
2006-05-02 01:31:56 +00:00
|
|
|
``IsAPowerOf``
|
|
|
|
Takes an integer argument and when called as a validator, checks that the
|
|
|
|
field being validated is a power of the integer.
|
|
|
|
|
|
|
|
``IsValidFloat``
|
|
|
|
Takes a maximum number of digits and number of decimal places (in that
|
|
|
|
order) and validates whether the field is a float with less than the
|
|
|
|
maximum number of digits and decimal place.
|
|
|
|
|
|
|
|
``MatchesRegularExpression``
|
|
|
|
Takes a regular expression (a string) as a parameter and validates the
|
|
|
|
field value against it.
|
|
|
|
|
|
|
|
``AnyValidator``
|
|
|
|
Takes a list of validators as a parameter. At validation time, if the
|
|
|
|
field successfully validates against any one of the validators, it passes
|
|
|
|
validation. The validators are tested in the order specified in the
|
|
|
|
original list.
|
|
|
|
|
|
|
|
``URLMimeTypeCheck``
|
|
|
|
Used to validate URL fields. Takes a list of MIME types (such as
|
|
|
|
``text/plain``) at creation time. At validation time, it verifies that the
|
|
|
|
field is indeed a URL and then tries to retrieve the content at the URL.
|
|
|
|
Validation succeeds if the content could be retrieved and it has a content
|
|
|
|
type from the list used to create the validator.
|
|
|
|
|
|
|
|
``RelaxNGCompact``
|
|
|
|
Used to validate an XML document against a Relax NG compact schema. Takes
|
|
|
|
a file path to the location of the schema and an optional root element
|
|
|
|
(which is wrapped around the XML fragment before validation, if supplied).
|
|
|
|
At validation time, the XML fragment is validated against the schema using
|
|
|
|
the executable specified in the ``JING_PATH`` setting (see the settings_
|
|
|
|
document for more details).
|
|
|
|
|
2007-01-24 20:08:47 +00:00
|
|
|
.. _`generic views`: ../generic_views/
|
|
|
|
.. _`models API`: ../model_api/
|
|
|
|
.. _settings: ../settings/
|