2008-08-23 22:25:40 +00:00
|
|
|
==========================
|
|
|
|
Creating forms from models
|
|
|
|
==========================
|
2007-12-02 19:29:54 +00:00
|
|
|
|
2010-10-23 22:06:01 +00:00
|
|
|
.. module:: django.forms.models
|
|
|
|
:synopsis: ModelForm and ModelFormset.
|
|
|
|
|
|
|
|
.. currentmodule:: django.forms
|
|
|
|
|
2007-12-02 19:29:54 +00:00
|
|
|
``ModelForm``
|
|
|
|
=============
|
2010-10-23 22:06:01 +00:00
|
|
|
.. class:: ModelForm
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
If you're building a database-driven app, chances are you'll have forms that
|
|
|
|
map closely to Django models. For instance, you might have a ``BlogComment``
|
|
|
|
model, and you want to create a form that lets people submit comments. In this
|
|
|
|
case, it would be redundant to define the field types in your form, because
|
|
|
|
you've already defined the fields in your model.
|
|
|
|
|
|
|
|
For this reason, Django provides a helper class that let you create a ``Form``
|
|
|
|
class from a Django model.
|
|
|
|
|
|
|
|
For example::
|
|
|
|
|
2008-07-21 16:38:54 +00:00
|
|
|
>>> from django.forms import ModelForm
|
2013-05-19 09:15:35 +00:00
|
|
|
>>> from myapp.models import Article
|
2008-01-28 03:12:28 +00:00
|
|
|
|
2007-12-02 19:29:54 +00:00
|
|
|
# Create the form class.
|
|
|
|
>>> class ArticleForm(ModelForm):
|
|
|
|
... class Meta:
|
|
|
|
... model = Article
|
2013-02-21 21:56:55 +00:00
|
|
|
... fields = ['pub_date', 'headline', 'content', 'reporter']
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
# Creating a form to add an article.
|
2007-12-13 02:48:04 +00:00
|
|
|
>>> form = ArticleForm()
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
# Creating a form to change an existing article.
|
|
|
|
>>> article = Article.objects.get(pk=1)
|
2007-12-13 02:48:04 +00:00
|
|
|
>>> form = ArticleForm(instance=article)
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
Field types
|
|
|
|
-----------
|
|
|
|
|
2013-02-21 21:56:55 +00:00
|
|
|
The generated ``Form`` class will have a form field for every model field
|
|
|
|
specified, in the order specified in the ``fields`` attribute.
|
|
|
|
|
|
|
|
Each model field has a corresponding default form field. For example, a
|
|
|
|
``CharField`` on a model is represented as a ``CharField`` on a form. A model
|
|
|
|
``ManyToManyField`` is represented as a ``MultipleChoiceField``. Here is the
|
|
|
|
full list of conversions:
|
2007-12-02 19:29:54 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
=============================== ========================================
|
|
|
|
Model field Form field
|
|
|
|
=============================== ========================================
|
|
|
|
``AutoField`` Not represented in the form
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``BigIntegerField`` ``IntegerField`` with ``min_value`` set
|
|
|
|
to -9223372036854775808 and ``max_value``
|
|
|
|
set to 9223372036854775807.
|
2009-12-17 15:10:38 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``BooleanField`` ``BooleanField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``CharField`` ``CharField`` with ``max_length`` set to
|
|
|
|
the model field's ``max_length``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``CommaSeparatedIntegerField`` ``CharField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``DateField`` ``DateField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``DateTimeField`` ``DateTimeField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``DecimalField`` ``DecimalField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``EmailField`` ``EmailField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``FileField`` ``FileField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2013-05-28 15:54:53 +00:00
|
|
|
``FilePathField`` ``FilePathField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``FloatField`` ``FloatField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``ForeignKey`` ``ModelChoiceField`` (see below)
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``ImageField`` ``ImageField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``IntegerField`` ``IntegerField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``IPAddressField`` ``IPAddressField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``GenericIPAddressField`` ``GenericIPAddressField``
|
2011-06-11 13:48:24 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``ManyToManyField`` ``ModelMultipleChoiceField`` (see
|
|
|
|
below)
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``NullBooleanField`` ``CharField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``PositiveIntegerField`` ``IntegerField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``PositiveSmallIntegerField`` ``IntegerField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``SlugField`` ``SlugField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``SmallIntegerField`` ``IntegerField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``TextField`` ``CharField`` with
|
|
|
|
``widget=forms.Textarea``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
``TimeField`` ``TimeField``
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2012-03-31 13:55:03 +00:00
|
|
|
``URLField`` ``URLField``
|
2011-10-14 00:12:01 +00:00
|
|
|
=============================== ========================================
|
2007-12-02 19:29:54 +00:00
|
|
|
|
2009-12-17 15:10:38 +00:00
|
|
|
|
2007-12-02 19:29:54 +00:00
|
|
|
As you might expect, the ``ForeignKey`` and ``ManyToManyField`` model field
|
|
|
|
types are special cases:
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* ``ForeignKey`` is represented by ``django.forms.ModelChoiceField``,
|
|
|
|
which is a ``ChoiceField`` whose choices are a model ``QuerySet``.
|
2007-12-02 19:29:54 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* ``ManyToManyField`` is represented by
|
|
|
|
``django.forms.ModelMultipleChoiceField``, which is a
|
|
|
|
``MultipleChoiceField`` whose choices are a model ``QuerySet``.
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
In addition, each generated form field has attributes set as follows:
|
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* If the model field has ``blank=True``, then ``required`` is set to
|
|
|
|
``False`` on the form field. Otherwise, ``required=True``.
|
2007-12-02 19:29:54 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* The form field's ``label`` is set to the ``verbose_name`` of the model
|
|
|
|
field, with the first character capitalized.
|
2007-12-02 19:29:54 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* The form field's ``help_text`` is set to the ``help_text`` of the model
|
|
|
|
field.
|
2007-12-02 19:29:54 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* If the model field has ``choices`` set, then the form field's ``widget``
|
|
|
|
will be set to ``Select``, with choices coming from the model field's
|
|
|
|
``choices``. The choices will normally include the blank choice which is
|
|
|
|
selected by default. If the field is required, this forces the user to
|
|
|
|
make a selection. The blank choice will not be included if the model
|
|
|
|
field has ``blank=False`` and an explicit ``default`` value (the
|
|
|
|
``default`` value will be initially selected instead).
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
Finally, note that you can override the form field used for a given model
|
2013-04-03 19:51:37 +00:00
|
|
|
field. See `Overriding the default fields`_ below.
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
A full example
|
|
|
|
--------------
|
|
|
|
|
|
|
|
Consider this set of models::
|
|
|
|
|
|
|
|
from django.db import models
|
2008-07-21 16:38:54 +00:00
|
|
|
from django.forms import ModelForm
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
TITLE_CHOICES = (
|
|
|
|
('MR', 'Mr.'),
|
|
|
|
('MRS', 'Mrs.'),
|
|
|
|
('MS', 'Ms.'),
|
|
|
|
)
|
|
|
|
|
|
|
|
class Author(models.Model):
|
|
|
|
name = models.CharField(max_length=100)
|
|
|
|
title = models.CharField(max_length=3, choices=TITLE_CHOICES)
|
|
|
|
birth_date = models.DateField(blank=True, null=True)
|
|
|
|
|
2013-07-04 13:19:33 +00:00
|
|
|
# On Python 3: def __str__(self):
|
2007-12-02 19:29:54 +00:00
|
|
|
def __unicode__(self):
|
|
|
|
return self.name
|
|
|
|
|
|
|
|
class Book(models.Model):
|
|
|
|
name = models.CharField(max_length=100)
|
|
|
|
authors = models.ManyToManyField(Author)
|
|
|
|
|
|
|
|
class AuthorForm(ModelForm):
|
|
|
|
class Meta:
|
|
|
|
model = Author
|
2013-02-21 21:56:55 +00:00
|
|
|
fields = ['name', 'title', 'birth_date']
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
class BookForm(ModelForm):
|
|
|
|
class Meta:
|
|
|
|
model = Book
|
2013-02-21 21:56:55 +00:00
|
|
|
fields = ['name', 'authors']
|
|
|
|
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
With these models, the ``ModelForm`` subclasses above would be roughly
|
|
|
|
equivalent to this (the only difference being the ``save()`` method, which
|
|
|
|
we'll discuss in a moment.)::
|
|
|
|
|
2011-08-06 19:02:20 +00:00
|
|
|
from django import forms
|
|
|
|
|
2007-12-02 19:29:54 +00:00
|
|
|
class AuthorForm(forms.Form):
|
|
|
|
name = forms.CharField(max_length=100)
|
|
|
|
title = forms.CharField(max_length=3,
|
|
|
|
widget=forms.Select(choices=TITLE_CHOICES))
|
|
|
|
birth_date = forms.DateField(required=False)
|
|
|
|
|
|
|
|
class BookForm(forms.Form):
|
|
|
|
name = forms.CharField(max_length=100)
|
|
|
|
authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all())
|
|
|
|
|
2013-07-16 19:27:52 +00:00
|
|
|
.. _validation-on-modelform:
|
2012-11-05 12:14:40 +00:00
|
|
|
|
2013-07-16 19:27:52 +00:00
|
|
|
Validation on a ``ModelForm``
|
|
|
|
-----------------------------
|
|
|
|
|
|
|
|
There are two main steps involved in validating a ``ModelForm``:
|
|
|
|
|
|
|
|
1. :ref:`Validating the form <form-and-field-validation>`
|
|
|
|
2. :ref:`Validating the model instance <validating-objects>`
|
|
|
|
|
|
|
|
Just like normal form validation, model form validation is triggered implicitly
|
|
|
|
when calling :meth:`~django.forms.Form.is_valid()` or accessing the
|
|
|
|
:attr:`~django.forms.Form.errors` attribute and explicitly when calling
|
|
|
|
``full_clean()``, although you will typically not use the latter method in
|
|
|
|
practice.
|
|
|
|
|
|
|
|
``Model`` validation (:meth:`Model.full_clean()
|
|
|
|
<django.db.models.Model.full_clean()>`) is triggered from within the form
|
|
|
|
validation step, right after the form's ``clean()`` method is called.
|
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
|
|
|
The cleaning process modifies the model instance passed to the
|
|
|
|
``ModelForm`` constructor in various ways. For instance, any date fields on
|
|
|
|
the model are converted into actual date objects. Failed validation may
|
|
|
|
leave the underlying model instance in an inconsistent state and therefore
|
|
|
|
it's not recommended to reuse it.
|
|
|
|
|
|
|
|
.. _overriding-modelform-clean-method:
|
|
|
|
|
|
|
|
Overriding the clean() method
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
2010-03-06 19:51:29 +00:00
|
|
|
|
2013-07-16 19:27:52 +00:00
|
|
|
You can override the ``clean()`` method on a model form to provide additional
|
|
|
|
validation in the same way you can on a normal form.
|
|
|
|
|
|
|
|
A model form instance bound to a model object will contain an ``instance``
|
|
|
|
attribute that gives its methods access to that specific model instance.
|
|
|
|
|
|
|
|
.. warning::
|
|
|
|
|
|
|
|
The ``ModelForm.clean()`` method sets a flag that makes the :ref:`model
|
|
|
|
validation <validating-objects>` step validate the uniqueness of model
|
|
|
|
fields that are marked as ``unique``, ``unique_together`` or
|
|
|
|
``unique_for_date|month|year``.
|
|
|
|
|
|
|
|
If you would like to override the ``clean()`` method and maintain this
|
|
|
|
validation, you must call the parent class's ``clean()`` method.
|
2010-03-06 19:51:29 +00:00
|
|
|
|
2013-07-16 19:27:52 +00:00
|
|
|
Interaction with model validation
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
As part of the validation process, ``ModelForm`` will call the ``clean()``
|
|
|
|
method of each field on your model that has a corresponding field on your form.
|
|
|
|
If you have excluded any model fields, validation will not be run on those
|
|
|
|
fields. See the :doc:`form validation </ref/forms/validation>` documentation
|
|
|
|
for more on how field cleaning and validation work.
|
|
|
|
|
|
|
|
The model's ``clean()`` method will be called before any uniqueness checks are
|
|
|
|
made. See :ref:`Validating objects <validating-objects>` for more information
|
|
|
|
on the model's ``clean()`` hook.
|
|
|
|
|
|
|
|
Considerations regarding fields' ``error_messages``
|
|
|
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
|
|
|
|
|
|
Error messages defined at the
|
|
|
|
:attr:`form field <django.forms.Field.error_messages>` level or at the
|
|
|
|
:ref:`form Meta <modelforms-overriding-default-fields>` level always take
|
|
|
|
precedence over the error messages defined at the
|
|
|
|
:attr:`model field <django.db.models.Field.error_messages>` level.
|
|
|
|
Error messages defined on :attr:`model fields
|
|
|
|
<django.db.models.Field.error_messages>` are only used when the
|
|
|
|
``ValidationError`` is raised during the :ref:`model validation
|
|
|
|
<validating-objects>` step and no corresponding error messages are defined at
|
|
|
|
the form level.
|
2010-03-06 19:51:29 +00:00
|
|
|
|
2007-12-02 19:29:54 +00:00
|
|
|
The ``save()`` method
|
|
|
|
---------------------
|
|
|
|
|
2013-07-16 19:27:52 +00:00
|
|
|
Every ``ModelForm`` also has a ``save()`` method. This method creates and saves
|
|
|
|
a database object from the data bound to the form. A subclass of ``ModelForm``
|
|
|
|
can accept an existing model instance as the keyword argument ``instance``; if
|
|
|
|
this is supplied, ``save()`` will update that instance. If it's not supplied,
|
2012-11-05 12:14:40 +00:00
|
|
|
``save()`` will create a new instance of the specified model:
|
|
|
|
|
|
|
|
.. code-block:: python
|
2007-12-02 19:29:54 +00:00
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
>>> from myapp.models import Article
|
|
|
|
>>> from myapp.forms import ArticleForm
|
|
|
|
|
2007-12-02 19:29:54 +00:00
|
|
|
# Create a form instance from POST data.
|
2007-12-13 02:48:04 +00:00
|
|
|
>>> f = ArticleForm(request.POST)
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
# Save a new Article object from the form's data.
|
|
|
|
>>> new_article = f.save()
|
|
|
|
|
2008-06-23 12:57:11 +00:00
|
|
|
# Create a form to edit an existing Article, but use
|
|
|
|
# POST data to populate the form.
|
|
|
|
>>> a = Article.objects.get(pk=1)
|
|
|
|
>>> f = ArticleForm(request.POST, instance=a)
|
|
|
|
>>> f.save()
|
2007-12-13 02:48:04 +00:00
|
|
|
|
2012-11-05 12:14:40 +00:00
|
|
|
Note that if the form :ref:`hasn't been validated
|
2013-07-16 19:27:52 +00:00
|
|
|
<validation-on-modelform>`, calling ``save()`` will do so by checking
|
2012-11-05 12:14:40 +00:00
|
|
|
``form.errors``. A ``ValueError`` will be raised if the data in the form
|
|
|
|
doesn't validate -- i.e., if ``form.errors`` evaluates to ``True``.
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
This ``save()`` method accepts an optional ``commit`` keyword argument, which
|
|
|
|
accepts either ``True`` or ``False``. If you call ``save()`` with
|
|
|
|
``commit=False``, then it will return an object that hasn't yet been saved to
|
|
|
|
the database. In this case, it's up to you to call ``save()`` on the resulting
|
|
|
|
model instance. This is useful if you want to do custom processing on the
|
2008-12-21 04:17:46 +00:00
|
|
|
object before saving it, or if you want to use one of the specialized
|
2008-12-23 00:01:09 +00:00
|
|
|
:ref:`model saving options <ref-models-force-insert>`. ``commit`` is ``True``
|
|
|
|
by default.
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
Another side effect of using ``commit=False`` is seen when your model has
|
|
|
|
a many-to-many relation with another model. If your model has a many-to-many
|
|
|
|
relation and you specify ``commit=False`` when you save a form, Django cannot
|
|
|
|
immediately save the form data for the many-to-many relation. This is because
|
|
|
|
it isn't possible to save many-to-many data for an instance until the instance
|
|
|
|
exists in the database.
|
|
|
|
|
|
|
|
To work around this problem, every time you save a form using ``commit=False``,
|
|
|
|
Django adds a ``save_m2m()`` method to your ``ModelForm`` subclass. After
|
|
|
|
you've manually saved the instance produced by the form, you can invoke
|
2013-07-16 19:27:52 +00:00
|
|
|
``save_m2m()`` to save the many-to-many form data. For example:
|
|
|
|
|
|
|
|
.. code-block:: python
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
# Create a form instance with POST data.
|
2007-12-13 02:48:04 +00:00
|
|
|
>>> f = AuthorForm(request.POST)
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
# Create, but don't save the new author instance.
|
|
|
|
>>> new_author = f.save(commit=False)
|
|
|
|
|
|
|
|
# Modify the author in some way.
|
|
|
|
>>> new_author.some_field = 'some_value'
|
|
|
|
|
|
|
|
# Save the new instance.
|
|
|
|
>>> new_author.save()
|
|
|
|
|
|
|
|
# Now, save the many-to-many data for the form.
|
|
|
|
>>> f.save_m2m()
|
|
|
|
|
|
|
|
Calling ``save_m2m()`` is only required if you use ``save(commit=False)``.
|
|
|
|
When you use a simple ``save()`` on a form, all data -- including
|
|
|
|
many-to-many data -- is saved without the need for any additional method calls.
|
2013-07-16 19:27:52 +00:00
|
|
|
For example:
|
|
|
|
|
|
|
|
.. code-block:: python
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
# Create a form instance with POST data.
|
|
|
|
>>> a = Author()
|
2008-03-11 06:40:50 +00:00
|
|
|
>>> f = AuthorForm(request.POST, instance=a)
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
# Create and save the new author instance. There's no need to do anything else.
|
|
|
|
>>> new_author = f.save()
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
Other than the ``save()`` and ``save_m2m()`` methods, a ``ModelForm`` works
|
|
|
|
exactly the same way as any other ``forms`` form. For example, the
|
|
|
|
``is_valid()`` method is used to check for validity, the ``is_multipart()``
|
|
|
|
method is used to determine whether a form requires multipart file upload (and
|
|
|
|
hence whether ``request.FILES`` must be passed to the form), etc. See
|
2009-05-24 06:46:02 +00:00
|
|
|
:ref:`binding-uploaded-files` for more information.
|
2008-03-18 21:13:12 +00:00
|
|
|
|
2013-02-21 21:56:55 +00:00
|
|
|
.. _modelforms-selecting-fields:
|
2007-12-02 19:29:54 +00:00
|
|
|
|
2013-02-21 21:56:55 +00:00
|
|
|
Selecting the fields to use
|
|
|
|
---------------------------
|
2007-12-02 19:29:54 +00:00
|
|
|
|
2013-02-21 21:56:55 +00:00
|
|
|
It is strongly recommended that you explicitly set all fields that should be
|
|
|
|
edited in the form using the ``fields`` attribute. Failure to do so can easily
|
|
|
|
lead to security problems when a form unexpectedly allows a user to set certain
|
|
|
|
fields, especially when new fields are added to a model. Depending on how the
|
|
|
|
form is rendered, the problem may not even be visible on the web page.
|
2007-12-02 19:29:54 +00:00
|
|
|
|
2013-02-21 21:56:55 +00:00
|
|
|
The alternative approach would be to include all fields automatically, or
|
|
|
|
blacklist only some. This fundamental approach is known to be much less secure
|
|
|
|
and has led to serious exploits on major websites (e.g. `GitHub
|
|
|
|
<https://github.com/blog/1068-public-key-security-vulnerability-and-mitigation>`_).
|
2007-12-02 19:29:54 +00:00
|
|
|
|
2013-02-21 21:56:55 +00:00
|
|
|
There are, however, two shortcuts available for cases where you can guarantee
|
|
|
|
these security concerns do not apply to you:
|
2007-12-02 19:29:54 +00:00
|
|
|
|
2013-02-21 21:56:55 +00:00
|
|
|
1. Set the ``fields`` attribute to the special value ``'__all__'`` to indicate
|
|
|
|
that all fields in the model should be used. For example::
|
2007-12-02 19:29:54 +00:00
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
from django.forms import ModelForm
|
|
|
|
|
2013-02-21 21:56:55 +00:00
|
|
|
class AuthorForm(ModelForm):
|
|
|
|
class Meta:
|
|
|
|
model = Author
|
|
|
|
fields = '__all__'
|
2008-12-23 00:01:09 +00:00
|
|
|
|
2013-02-21 21:56:55 +00:00
|
|
|
2. Set the ``exclude`` attribute of the ``ModelForm``'s inner ``Meta`` class to
|
|
|
|
a list of fields to be excluded from the form.
|
|
|
|
|
|
|
|
For example::
|
|
|
|
|
|
|
|
class PartialAuthorForm(ModelForm):
|
|
|
|
class Meta:
|
|
|
|
model = Author
|
|
|
|
exclude = ['title']
|
|
|
|
|
|
|
|
Since the ``Author`` model has the 3 fields ``name``, ``title`` and
|
|
|
|
``birth_date``, this will result in the fields ``name`` and ``birth_date``
|
|
|
|
being present on the form.
|
|
|
|
|
|
|
|
If either of these are used, the order the fields appear in the form will be the
|
|
|
|
order the fields are defined in the model, with ``ManyToManyField`` instances
|
|
|
|
appearing last.
|
|
|
|
|
|
|
|
In addition, Django applies the following rule: if you set ``editable=False`` on
|
|
|
|
the model field, *any* form created from the model via ``ModelForm`` will not
|
|
|
|
include that field.
|
|
|
|
|
|
|
|
.. versionchanged:: 1.6
|
|
|
|
|
|
|
|
Before version 1.6, the ``'__all__'`` shortcut did not exist, but omitting
|
|
|
|
the ``fields`` attribute had the same effect. Omitting both ``fields`` and
|
|
|
|
``exclude`` is now deprecated, but will continue to work as before until
|
|
|
|
version 1.8
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
|
|
|
|
.. note::
|
|
|
|
|
2013-02-21 21:56:55 +00:00
|
|
|
Any fields not included in a form by the above logic
|
2011-09-22 04:52:43 +00:00
|
|
|
will not be set by the form's ``save()`` method. Also, if you
|
|
|
|
manually add the excluded fields back to the form, they will not
|
|
|
|
be initialized from the model instance.
|
|
|
|
|
|
|
|
Django will prevent any attempt to save an incomplete model, so if
|
|
|
|
the model does not allow the missing fields to be empty, and does
|
|
|
|
not provide a default value for the missing fields, any attempt to
|
|
|
|
``save()`` a ``ModelForm`` with missing fields will fail. To
|
|
|
|
avoid this failure, you must instantiate your model with initial
|
|
|
|
values for the missing, but required fields::
|
2008-01-28 03:12:28 +00:00
|
|
|
|
2009-06-10 12:46:04 +00:00
|
|
|
author = Author(title='Mr')
|
|
|
|
form = PartialAuthorForm(request.POST, instance=author)
|
|
|
|
form.save()
|
2007-12-02 19:29:54 +00:00
|
|
|
|
2009-06-10 12:46:04 +00:00
|
|
|
Alternatively, you can use ``save(commit=False)`` and manually set
|
|
|
|
any extra required fields::
|
|
|
|
|
|
|
|
form = PartialAuthorForm(request.POST)
|
|
|
|
author = form.save(commit=False)
|
|
|
|
author.title = 'Mr'
|
|
|
|
author.save()
|
2007-12-02 19:29:54 +00:00
|
|
|
|
|
|
|
See the `section on saving forms`_ for more details on using
|
|
|
|
``save(commit=False)``.
|
|
|
|
|
|
|
|
.. _section on saving forms: `The save() method`_
|
|
|
|
|
2013-04-03 19:51:37 +00:00
|
|
|
.. _modelforms-overriding-default-fields:
|
|
|
|
|
|
|
|
Overriding the default fields
|
|
|
|
-----------------------------
|
2007-12-02 19:29:54 +00:00
|
|
|
|
2008-01-28 02:56:35 +00:00
|
|
|
The default field types, as described in the `Field types`_ table above, are
|
2007-12-19 03:39:21 +00:00
|
|
|
sensible defaults. If you have a ``DateField`` in your model, chances are you'd
|
2007-12-02 19:29:54 +00:00
|
|
|
want that to be represented as a ``DateField`` in your form. But
|
2010-03-27 23:03:56 +00:00
|
|
|
``ModelForm`` gives you the flexibility of changing the form field type and
|
2010-01-10 19:23:42 +00:00
|
|
|
widget for a given model field.
|
|
|
|
|
|
|
|
To specify a custom widget for a field, use the ``widgets`` attribute of the
|
|
|
|
inner ``Meta`` class. This should be a dictionary mapping field names to widget
|
|
|
|
classes or instances.
|
|
|
|
|
2010-05-08 07:32:31 +00:00
|
|
|
For example, if you want the a ``CharField`` for the ``name``
|
|
|
|
attribute of ``Author`` to be represented by a ``<textarea>`` instead
|
|
|
|
of its default ``<input type="text">``, you can override the field's
|
|
|
|
widget::
|
|
|
|
|
2010-05-17 00:27:37 +00:00
|
|
|
from django.forms import ModelForm, Textarea
|
2013-05-19 09:15:35 +00:00
|
|
|
from myapp.models import Author
|
2010-01-10 19:23:42 +00:00
|
|
|
|
|
|
|
class AuthorForm(ModelForm):
|
|
|
|
class Meta:
|
|
|
|
model = Author
|
2010-10-10 22:40:54 +00:00
|
|
|
fields = ('name', 'title', 'birth_date')
|
2010-01-10 19:23:42 +00:00
|
|
|
widgets = {
|
|
|
|
'name': Textarea(attrs={'cols': 80, 'rows': 20}),
|
|
|
|
}
|
|
|
|
|
|
|
|
The ``widgets`` dictionary accepts either widget instances (e.g.,
|
|
|
|
``Textarea(...)``) or classes (e.g., ``Textarea``).
|
|
|
|
|
2013-04-03 19:51:37 +00:00
|
|
|
.. versionadded:: 1.6
|
|
|
|
|
|
|
|
The ``labels``, ``help_texts`` and ``error_messages`` options were added.
|
|
|
|
|
|
|
|
Similarly, you can specify the ``labels``, ``help_texts`` and ``error_messages``
|
|
|
|
attributes of the inner ``Meta`` class if you want to further customize a field.
|
2007-12-02 19:29:54 +00:00
|
|
|
|
2013-04-03 19:51:37 +00:00
|
|
|
For example if you wanted to customize the wording of all user facing strings for
|
|
|
|
the ``name`` field::
|
|
|
|
|
|
|
|
class AuthorForm(ModelForm):
|
|
|
|
class Meta:
|
|
|
|
model = Author
|
|
|
|
fields = ('name', 'title', 'birth_date')
|
|
|
|
labels = {
|
|
|
|
'name': _('Writer'),
|
|
|
|
}
|
|
|
|
help_texts = {
|
|
|
|
'name': _('Some useful help text.'),
|
|
|
|
}
|
|
|
|
error_messages = {
|
|
|
|
'name': {
|
|
|
|
'max_length': _("This writer's name is too long."),
|
|
|
|
},
|
|
|
|
}
|
|
|
|
|
|
|
|
Finally, if you want complete control over of a field -- including its type,
|
|
|
|
validators, etc. -- you can do this by declaratively specifying fields like you
|
|
|
|
would in a regular ``Form``. Declared fields will override the default ones
|
|
|
|
generated by using the ``model`` attribute. Fields declared like this will
|
|
|
|
ignore any customizations in the ``widgets``, ``labels``, ``help_texts``, and
|
|
|
|
``error_messages`` options declared on ``Meta``.
|
|
|
|
|
|
|
|
For example, if you wanted to use ``MySlugFormField`` for the ``slug``
|
2007-12-02 19:29:54 +00:00
|
|
|
field, you could do the following::
|
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
from django.forms import ModelForm
|
|
|
|
from myapp.models import Article
|
|
|
|
|
2010-01-10 19:23:42 +00:00
|
|
|
class ArticleForm(ModelForm):
|
2013-04-03 19:51:37 +00:00
|
|
|
slug = MySlugFormField()
|
2010-03-27 23:03:56 +00:00
|
|
|
|
2010-01-10 19:23:42 +00:00
|
|
|
class Meta:
|
|
|
|
model = Article
|
2013-02-21 21:56:55 +00:00
|
|
|
fields = ['pub_date', 'headline', 'content', 'reporter']
|
|
|
|
|
2008-01-28 03:12:28 +00:00
|
|
|
|
2013-04-03 19:51:37 +00:00
|
|
|
If you want to override a field's default validators, then specify the
|
|
|
|
``validators`` parameter when declaring the form field::
|
2008-01-28 03:12:28 +00:00
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
from django.forms import ModelForm, DateField
|
|
|
|
from myapp.models import Article
|
|
|
|
|
2013-02-21 21:56:55 +00:00
|
|
|
class ArticleForm(ModelForm):
|
2013-04-03 19:51:37 +00:00
|
|
|
slug = CharField(validators=[validate_slug])
|
2013-02-21 21:56:55 +00:00
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = Article
|
2013-04-03 19:51:37 +00:00
|
|
|
fields = ['pub_date', 'headline', 'content', 'reporter', 'slug']
|
2008-02-14 12:56:49 +00:00
|
|
|
|
2009-09-13 01:35:18 +00:00
|
|
|
.. note::
|
|
|
|
|
|
|
|
If you explicitly instantiate a form field like this, Django assumes that you
|
2009-09-13 03:01:04 +00:00
|
|
|
want to completely define its behavior; therefore, default attributes (such as
|
|
|
|
``max_length`` or ``required``) are not drawn from the corresponding model. If
|
2009-09-13 01:35:18 +00:00
|
|
|
you want to maintain the behavior specified in the model, you must set the
|
|
|
|
relevant arguments explicitly when declaring the form field.
|
|
|
|
|
|
|
|
For example, if the ``Article`` model looks like this::
|
|
|
|
|
|
|
|
class Article(models.Model):
|
2009-09-13 03:01:04 +00:00
|
|
|
headline = models.CharField(max_length=200, null=True, blank=True,
|
2009-09-13 01:35:18 +00:00
|
|
|
help_text="Use puns liberally")
|
|
|
|
content = models.TextField()
|
|
|
|
|
|
|
|
and you want to do some custom validation for ``headline``, while keeping
|
2009-09-13 03:01:04 +00:00
|
|
|
the ``blank`` and ``help_text`` values as specified, you might define
|
2009-09-13 01:35:18 +00:00
|
|
|
``ArticleForm`` like this::
|
|
|
|
|
|
|
|
class ArticleForm(ModelForm):
|
2009-09-13 03:01:04 +00:00
|
|
|
headline = MyFormField(max_length=200, required=False,
|
2009-09-13 01:35:18 +00:00
|
|
|
help_text="Use puns liberally")
|
|
|
|
|
|
|
|
class Meta:
|
|
|
|
model = Article
|
2013-02-21 21:56:55 +00:00
|
|
|
fields = ['headline', 'content']
|
2009-09-13 01:35:18 +00:00
|
|
|
|
2012-07-31 20:20:41 +00:00
|
|
|
You must ensure that the type of the form field can be used to set the
|
|
|
|
contents of the corresponding model field. When they are not compatible,
|
|
|
|
you will get a ``ValueError`` as no implicit conversion takes place.
|
|
|
|
|
2010-08-19 19:27:44 +00:00
|
|
|
See the :doc:`form field documentation </ref/forms/fields>` for more information
|
2009-09-13 01:35:18 +00:00
|
|
|
on fields and their arguments.
|
|
|
|
|
2013-05-18 12:13:00 +00:00
|
|
|
|
|
|
|
Enabling localization of fields
|
|
|
|
-------------------------------
|
|
|
|
|
|
|
|
.. versionadded:: 1.6
|
|
|
|
|
|
|
|
By default, the fields in a ``ModelForm`` will not localize their data. To
|
|
|
|
enable localization for fields, you can use the ``localized_fields``
|
|
|
|
attribute on the ``Meta`` class.
|
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
>>> from django.forms import ModelForm
|
|
|
|
>>> from myapp.models import Author
|
2013-05-18 12:13:00 +00:00
|
|
|
>>> class AuthorForm(ModelForm):
|
|
|
|
... class Meta:
|
|
|
|
... model = Author
|
|
|
|
... localized_fields = ('birth_date',)
|
|
|
|
|
|
|
|
If ``localized_fields`` is set to the special value ``'__all__'``, all fields
|
|
|
|
will be localized.
|
|
|
|
|
2008-02-14 12:56:49 +00:00
|
|
|
Form inheritance
|
|
|
|
----------------
|
2008-02-16 05:15:09 +00:00
|
|
|
|
|
|
|
As with basic forms, you can extend and reuse ``ModelForms`` by inheriting
|
|
|
|
them. This is useful if you need to declare extra fields or extra methods on a
|
|
|
|
parent class for use in a number of forms derived from models. For example,
|
|
|
|
using the previous ``ArticleForm`` class::
|
2008-02-14 12:56:49 +00:00
|
|
|
|
|
|
|
>>> class EnhancedArticleForm(ArticleForm):
|
|
|
|
... def clean_pub_date(self):
|
|
|
|
... ...
|
|
|
|
|
2008-02-16 05:15:09 +00:00
|
|
|
This creates a form that behaves identically to ``ArticleForm``, except there's
|
|
|
|
some extra validation and cleaning for the ``pub_date`` field.
|
2008-02-14 12:56:49 +00:00
|
|
|
|
2008-02-14 17:38:05 +00:00
|
|
|
You can also subclass the parent's ``Meta`` inner class if you want to change
|
|
|
|
the ``Meta.fields`` or ``Meta.excludes`` lists::
|
|
|
|
|
|
|
|
>>> class RestrictedArticleForm(EnhancedArticleForm):
|
|
|
|
... class Meta(ArticleForm.Meta):
|
2010-10-10 22:40:54 +00:00
|
|
|
... exclude = ('body',)
|
2008-02-14 17:38:05 +00:00
|
|
|
|
2008-02-16 05:15:09 +00:00
|
|
|
This adds the extra method from the ``EnhancedArticleForm`` and modifies
|
2008-02-14 17:38:05 +00:00
|
|
|
the original ``ArticleForm.Meta`` to remove one field.
|
|
|
|
|
2008-02-16 05:15:09 +00:00
|
|
|
There are a couple of things to note, however.
|
2008-02-14 12:56:49 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* Normal Python name resolution rules apply. If you have multiple base
|
|
|
|
classes that declare a ``Meta`` inner class, only the first one will be
|
|
|
|
used. This means the child's ``Meta``, if it exists, otherwise the
|
|
|
|
``Meta`` of the first parent, etc.
|
2008-02-14 12:56:49 +00:00
|
|
|
|
2011-10-14 00:12:01 +00:00
|
|
|
* For technical reasons, a subclass cannot inherit from both a ``ModelForm``
|
|
|
|
and a ``Form`` simultaneously.
|
2008-02-14 12:56:49 +00:00
|
|
|
|
2008-02-16 05:15:09 +00:00
|
|
|
Chances are these notes won't affect you unless you're trying to do something
|
|
|
|
tricky with subclassing.
|
2008-07-18 23:54:34 +00:00
|
|
|
|
2013-01-11 10:59:17 +00:00
|
|
|
.. _modelforms-factory:
|
|
|
|
|
|
|
|
ModelForm factory function
|
|
|
|
--------------------------
|
|
|
|
|
|
|
|
You can create forms from a given model using the standalone function
|
2013-01-22 11:46:22 +00:00
|
|
|
:func:`~django.forms.models.modelform_factory`, instead of using a class
|
2013-01-11 10:59:17 +00:00
|
|
|
definition. This may be more convenient if you do not have many customizations
|
|
|
|
to make::
|
|
|
|
|
|
|
|
>>> from django.forms.models import modelform_factory
|
2013-05-19 09:15:35 +00:00
|
|
|
>>> from myapp.models import Book
|
2013-02-21 21:56:55 +00:00
|
|
|
>>> BookForm = modelform_factory(Book, fields=("author", "title"))
|
2013-01-11 10:59:17 +00:00
|
|
|
|
|
|
|
This can also be used to make simple modifications to existing forms, for
|
2013-02-21 21:56:55 +00:00
|
|
|
example by specifying the widgets to be used for a given field::
|
2013-01-11 10:59:17 +00:00
|
|
|
|
|
|
|
>>> from django.forms import Textarea
|
2013-02-21 21:56:55 +00:00
|
|
|
>>> Form = modelform_factory(Book, form=BookForm,
|
2013-04-03 19:51:37 +00:00
|
|
|
... widgets={"title": Textarea()})
|
2013-02-21 21:56:55 +00:00
|
|
|
|
|
|
|
The fields to include can be specified using the ``fields`` and ``exclude``
|
|
|
|
keyword arguments, or the corresponding attributes on the ``ModelForm`` inner
|
|
|
|
``Meta`` class. Please see the ``ModelForm`` :ref:`modelforms-selecting-fields`
|
|
|
|
documentation.
|
2013-01-11 10:59:17 +00:00
|
|
|
|
2013-05-18 12:13:00 +00:00
|
|
|
... or enable localization for specific fields::
|
|
|
|
|
|
|
|
>>> Form = modelform_factory(Author, form=AuthorForm, localized_fields=("birth_date",))
|
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
.. _model-formsets:
|
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
Model formsets
|
2008-07-18 23:54:34 +00:00
|
|
|
==============
|
|
|
|
|
2012-12-29 15:35:12 +00:00
|
|
|
.. class:: models.BaseModelFormSet
|
|
|
|
|
2010-08-19 19:27:44 +00:00
|
|
|
Like :doc:`regular formsets </topics/forms/formsets>`, Django provides a couple
|
2008-12-09 04:17:14 +00:00
|
|
|
of enhanced formset classes that make it easy to work with Django models. Let's
|
|
|
|
reuse the ``Author`` model from above::
|
2008-07-18 23:54:34 +00:00
|
|
|
|
2008-07-21 16:56:52 +00:00
|
|
|
>>> from django.forms.models import modelformset_factory
|
2013-05-19 09:15:35 +00:00
|
|
|
>>> from myapp.models import Author
|
2008-07-18 23:54:34 +00:00
|
|
|
>>> AuthorFormSet = modelformset_factory(Author)
|
|
|
|
|
|
|
|
This will create a formset that is capable of working with the data associated
|
2008-12-09 04:17:14 +00:00
|
|
|
with the ``Author`` model. It works just like a regular formset::
|
2008-07-18 23:54:34 +00:00
|
|
|
|
|
|
|
>>> formset = AuthorFormSet()
|
2012-04-28 16:02:01 +00:00
|
|
|
>>> print(formset)
|
2010-03-27 23:03:56 +00:00
|
|
|
<input type="hidden" name="form-TOTAL_FORMS" value="1" id="id_form-TOTAL_FORMS" /><input type="hidden" name="form-INITIAL_FORMS" value="0" id="id_form-INITIAL_FORMS" /><input type="hidden" name="form-MAX_NUM_FORMS" id="id_form-MAX_NUM_FORMS" />
|
2008-07-18 23:54:34 +00:00
|
|
|
<tr><th><label for="id_form-0-name">Name:</label></th><td><input id="id_form-0-name" type="text" name="form-0-name" maxlength="100" /></td></tr>
|
|
|
|
<tr><th><label for="id_form-0-title">Title:</label></th><td><select name="form-0-title" id="id_form-0-title">
|
|
|
|
<option value="" selected="selected">---------</option>
|
|
|
|
<option value="MR">Mr.</option>
|
|
|
|
<option value="MRS">Mrs.</option>
|
|
|
|
<option value="MS">Ms.</option>
|
|
|
|
</select></td></tr>
|
|
|
|
<tr><th><label for="id_form-0-birth_date">Birth date:</label></th><td><input type="text" name="form-0-birth_date" id="id_form-0-birth_date" /><input type="hidden" name="form-0-id" id="id_form-0-id" /></td></tr>
|
|
|
|
|
|
|
|
.. note::
|
2013-01-11 10:59:17 +00:00
|
|
|
|
Fixed #20084 -- Provided option to validate formset max_num on server.
This is provided as a new "validate_max" formset_factory option defaulting to
False, since the non-validating behavior of max_num is longstanding, and there
is certainly code relying on it. (In fact, even the Django admin relies on it
for the case where there are more existing inlines than the given max_num). It
may be that at some point we want to deprecate validate_max=False and
eventually remove the option, but this commit takes no steps in that direction.
This also fixes the DoS-prevention absolute_max enforcement so that it causes a
form validation error rather than an IndexError, and ensures that absolute_max
is always 1000 more than max_num, to prevent surprising changes in behavior
with max_num close to absolute_max.
Lastly, this commit fixes the previous inconsistency between a regular formset
and a model formset in the precedence of max_num and initial data. Previously
in a regular formset, if the provided initial data was longer than max_num, it
was truncated; in a model formset, all initial forms would be displayed
regardless of max_num. Now regular formsets are the same as model formsets; all
initial forms are displayed, even if more than max_num. (But if validate_max is
True, submitting these forms will result in a "too many forms" validation
error!) This combination of behaviors was chosen to keep the max_num validation
simple and consistent, and avoid silent data loss due to truncation of initial
data.
Thanks to Preston for discussion of the design choices.
2013-03-21 06:27:06 +00:00
|
|
|
:func:`~django.forms.models.modelformset_factory` uses
|
|
|
|
:func:`~django.forms.formsets.formset_factory` to generate formsets. This
|
|
|
|
means that a model formset is just an extension of a basic formset that
|
|
|
|
knows how to interact with a particular model.
|
2008-07-18 23:54:34 +00:00
|
|
|
|
|
|
|
Changing the queryset
|
|
|
|
---------------------
|
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
By default, when you create a formset from a model, the formset will use a
|
|
|
|
queryset that includes all objects in the model (e.g.,
|
|
|
|
``Author.objects.all()``). You can override this behavior by using the
|
|
|
|
``queryset`` argument::
|
2008-07-18 23:54:34 +00:00
|
|
|
|
|
|
|
>>> formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O'))
|
|
|
|
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 18:30:54 +00:00
|
|
|
Alternatively, you can create a subclass that sets ``self.queryset`` in
|
|
|
|
``__init__``::
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2008-07-21 16:56:52 +00:00
|
|
|
from django.forms.models import BaseModelFormSet
|
2013-05-19 09:15:35 +00:00
|
|
|
from myapp.models import Author
|
2008-12-23 00:01:09 +00:00
|
|
|
|
2008-07-18 23:54:34 +00:00
|
|
|
class BaseAuthorFormSet(BaseModelFormSet):
|
Fixed a whole bunch of small docs typos, errors, and ommissions.
Fixes #8358, #8396, #8724, #9043, #9128, #9247, #9267, #9267, #9375, #9409, #9414, #9416, #9446, #9454, #9464, #9503, #9518, #9533, #9657, #9658, #9683, #9733, #9771, #9835, #9836, #9837, #9897, #9906, #9912, #9945, #9986, #9992, #10055, #10084, #10091, #10145, #10245, #10257, #10309, #10358, #10359, #10424, #10426, #10508, #10531, #10551, #10635, #10637, #10656, #10658, #10690, #10699, #19528.
Thanks to all the respective authors of those tickets.
git-svn-id: http://code.djangoproject.com/svn/django/trunk@10371 bcc190cf-cafb-0310-a4f2-bffc1f526a37
2009-04-03 18:30:54 +00:00
|
|
|
def __init__(self, *args, **kwargs):
|
|
|
|
super(BaseAuthorFormSet, self).__init__(*args, **kwargs)
|
2010-08-07 14:56:38 +00:00
|
|
|
self.queryset = Author.objects.filter(name__startswith='O')
|
2008-07-18 23:54:34 +00:00
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
Then, pass your ``BaseAuthorFormSet`` class to the factory function::
|
2008-07-18 23:54:34 +00:00
|
|
|
|
|
|
|
>>> AuthorFormSet = modelformset_factory(Author, formset=BaseAuthorFormSet)
|
|
|
|
|
2009-09-13 03:01:04 +00:00
|
|
|
If you want to return a formset that doesn't include *any* pre-existing
|
|
|
|
instances of the model, you can specify an empty QuerySet::
|
|
|
|
|
|
|
|
>>> AuthorFormSet(queryset=Author.objects.none())
|
|
|
|
|
|
|
|
|
2008-09-02 17:57:18 +00:00
|
|
|
Controlling which fields are used with ``fields`` and ``exclude``
|
|
|
|
-----------------------------------------------------------------
|
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
By default, a model formset uses all fields in the model that are not marked
|
|
|
|
with ``editable=False``. However, this can be overridden at the formset level::
|
2008-09-02 17:57:18 +00:00
|
|
|
|
|
|
|
>>> AuthorFormSet = modelformset_factory(Author, fields=('name', 'title'))
|
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
Using ``fields`` restricts the formset to use only the given fields.
|
|
|
|
Alternatively, you can take an "opt-out" approach, specifying which fields to
|
|
|
|
exclude::
|
2008-09-02 17:57:18 +00:00
|
|
|
|
|
|
|
>>> AuthorFormSet = modelformset_factory(Author, exclude=('birth_date',))
|
|
|
|
|
2013-01-23 20:11:46 +00:00
|
|
|
Specifying widgets to use in the form with ``widgets``
|
|
|
|
------------------------------------------------------
|
|
|
|
|
|
|
|
.. versionadded:: 1.6
|
|
|
|
|
|
|
|
Using the ``widgets`` parameter, you can specify a dictionary of values to
|
|
|
|
customize the ``ModelForm``'s widget class for a particular field. This
|
|
|
|
works the same way as the ``widgets`` dictionary on the inner ``Meta``
|
|
|
|
class of a ``ModelForm`` works::
|
|
|
|
|
|
|
|
>>> AuthorFormSet = modelformset_factory(
|
|
|
|
... Author, widgets={'name': Textarea(attrs={'cols': 80, 'rows': 20})
|
|
|
|
|
2013-05-18 12:13:00 +00:00
|
|
|
Enabling localization for fields with ``localized_fields``
|
|
|
|
----------------------------------------------------------
|
|
|
|
|
|
|
|
.. versionadded:: 1.6
|
|
|
|
|
|
|
|
Using the ``localized_fields`` parameter, you can enable localization for
|
|
|
|
fields in the form.
|
|
|
|
|
|
|
|
>>> AuthorFormSet = modelformset_factory(
|
|
|
|
... Author, localized_fields=('value',))
|
|
|
|
|
|
|
|
If ``localized_fields`` is set to the special value ``'__all__'``, all fields
|
|
|
|
will be localized.
|
|
|
|
|
2012-01-15 01:36:14 +00:00
|
|
|
Providing initial values
|
|
|
|
------------------------
|
|
|
|
|
2012-02-03 20:45:45 +00:00
|
|
|
As with regular formsets, it's possible to :ref:`specify initial data
|
2012-01-15 01:36:14 +00:00
|
|
|
<formsets-initial-data>` for forms in the formset by specifying an ``initial``
|
|
|
|
parameter when instantiating the model formset class returned by
|
2013-01-11 10:59:17 +00:00
|
|
|
:func:`~django.forms.models.modelformset_factory`. However, with model
|
|
|
|
formsets, the initial values only apply to extra forms, those that aren't bound
|
|
|
|
to an existing object instance.
|
2012-01-15 01:36:14 +00:00
|
|
|
|
2008-09-02 17:57:18 +00:00
|
|
|
.. _saving-objects-in-the-formset:
|
|
|
|
|
2008-07-18 23:54:34 +00:00
|
|
|
Saving objects in the formset
|
|
|
|
-----------------------------
|
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
As with a ``ModelForm``, you can save the data as a model object. This is done
|
|
|
|
with the formset's ``save()`` method::
|
2008-07-18 23:54:34 +00:00
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
# Create a formset instance with POST data.
|
2008-07-18 23:54:34 +00:00
|
|
|
>>> formset = AuthorFormSet(request.POST)
|
2008-12-09 04:17:14 +00:00
|
|
|
|
|
|
|
# Assuming all is valid, save the data.
|
2008-07-18 23:54:34 +00:00
|
|
|
>>> instances = formset.save()
|
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
The ``save()`` method returns the instances that have been saved to the
|
|
|
|
database. If a given instance's data didn't change in the bound data, the
|
|
|
|
instance won't be saved to the database and won't be included in the return
|
|
|
|
value (``instances``, in the above example).
|
2008-07-18 23:54:34 +00:00
|
|
|
|
2013-02-21 21:56:55 +00:00
|
|
|
When fields are missing from the form (for example because they have been
|
|
|
|
excluded), these fields will not be set by the ``save()`` method. You can find
|
|
|
|
more information about this restriction, which also holds for regular
|
|
|
|
``ModelForms``, in `Selecting the fields to use`_.
|
2011-09-22 04:52:43 +00:00
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
Pass ``commit=False`` to return the unsaved model instances::
|
2008-07-18 23:54:34 +00:00
|
|
|
|
|
|
|
# don't save to the database
|
|
|
|
>>> instances = formset.save(commit=False)
|
|
|
|
>>> for instance in instances:
|
|
|
|
... # do something with instance
|
|
|
|
... instance.save()
|
|
|
|
|
|
|
|
This gives you the ability to attach data to the instances before saving them
|
2008-12-09 04:17:14 +00:00
|
|
|
to the database. If your formset contains a ``ManyToManyField``, you'll also
|
|
|
|
need to call ``formset.save_m2m()`` to ensure the many-to-many relationships
|
|
|
|
are saved properly.
|
2008-07-18 23:54:34 +00:00
|
|
|
|
2008-08-23 22:25:40 +00:00
|
|
|
.. _model-formsets-max-num:
|
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
Limiting the number of editable objects
|
2008-07-18 23:54:34 +00:00
|
|
|
---------------------------------------
|
|
|
|
|
2010-05-12 11:56:42 +00:00
|
|
|
As with regular formsets, you can use the ``max_num`` and ``extra`` parameters
|
2013-01-11 10:59:17 +00:00
|
|
|
to :func:`~django.forms.models.modelformset_factory` to limit the number of
|
|
|
|
extra forms displayed.
|
2010-03-27 23:03:56 +00:00
|
|
|
|
|
|
|
``max_num`` does not prevent existing objects from being displayed::
|
2008-07-18 23:54:34 +00:00
|
|
|
|
|
|
|
>>> Author.objects.order_by('name')
|
|
|
|
[<Author: Charles Baudelaire>, <Author: Paul Verlaine>, <Author: Walt Whitman>]
|
2008-12-23 00:01:09 +00:00
|
|
|
|
2010-03-27 23:03:56 +00:00
|
|
|
>>> AuthorFormSet = modelformset_factory(Author, max_num=1)
|
2008-07-18 23:54:34 +00:00
|
|
|
>>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
|
2010-03-27 23:03:56 +00:00
|
|
|
>>> [x.name for x in formset.get_queryset()]
|
|
|
|
[u'Charles Baudelaire', u'Paul Verlaine', u'Walt Whitman']
|
2008-07-18 23:54:34 +00:00
|
|
|
|
2010-05-12 22:53:23 +00:00
|
|
|
If the value of ``max_num`` is greater than the number of existing related
|
2010-03-27 23:03:56 +00:00
|
|
|
objects, up to ``extra`` additional blank forms will be added to the formset,
|
|
|
|
so long as the total number of forms does not exceed ``max_num``::
|
2008-07-18 23:54:34 +00:00
|
|
|
|
2009-05-18 16:00:29 +00:00
|
|
|
>>> AuthorFormSet = modelformset_factory(Author, max_num=4, extra=2)
|
2008-07-18 23:54:34 +00:00
|
|
|
>>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
|
2010-12-19 13:41:43 +00:00
|
|
|
>>> for form in formset:
|
2012-04-28 16:02:01 +00:00
|
|
|
... print(form.as_table())
|
2008-07-18 23:54:34 +00:00
|
|
|
<tr><th><label for="id_form-0-name">Name:</label></th><td><input id="id_form-0-name" type="text" name="form-0-name" value="Charles Baudelaire" maxlength="100" /><input type="hidden" name="form-0-id" value="1" id="id_form-0-id" /></td></tr>
|
|
|
|
<tr><th><label for="id_form-1-name">Name:</label></th><td><input id="id_form-1-name" type="text" name="form-1-name" value="Paul Verlaine" maxlength="100" /><input type="hidden" name="form-1-id" value="3" id="id_form-1-id" /></td></tr>
|
|
|
|
<tr><th><label for="id_form-2-name">Name:</label></th><td><input id="id_form-2-name" type="text" name="form-2-name" value="Walt Whitman" maxlength="100" /><input type="hidden" name="form-2-id" value="2" id="id_form-2-id" /></td></tr>
|
|
|
|
<tr><th><label for="id_form-3-name">Name:</label></th><td><input id="id_form-3-name" type="text" name="form-3-name" maxlength="100" /><input type="hidden" name="form-3-id" id="id_form-3-id" /></td></tr>
|
|
|
|
|
2013-02-12 10:22:41 +00:00
|
|
|
A ``max_num`` value of ``None`` (the default) puts a high limit on the number
|
|
|
|
of forms displayed (1000). In practice this is equivalent to no limit.
|
2010-03-27 23:03:56 +00:00
|
|
|
|
2008-09-02 17:57:02 +00:00
|
|
|
Using a model formset in a view
|
|
|
|
-------------------------------
|
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
Model formsets are very similar to formsets. Let's say we want to present a
|
|
|
|
formset to edit ``Author`` model instances::
|
2008-09-02 17:57:02 +00:00
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
from django.forms.models import modelformset_factory
|
|
|
|
from django.shortcuts import render_to_response
|
|
|
|
from myapp.models import Author
|
|
|
|
|
2008-09-02 17:57:02 +00:00
|
|
|
def manage_authors(request):
|
|
|
|
AuthorFormSet = modelformset_factory(Author)
|
2008-09-12 15:52:39 +00:00
|
|
|
if request.method == 'POST':
|
2008-09-02 17:57:02 +00:00
|
|
|
formset = AuthorFormSet(request.POST, request.FILES)
|
|
|
|
if formset.is_valid():
|
|
|
|
formset.save()
|
|
|
|
# do something.
|
|
|
|
else:
|
|
|
|
formset = AuthorFormSet()
|
2008-12-09 00:31:17 +00:00
|
|
|
return render_to_response("manage_authors.html", {
|
2008-09-02 17:57:02 +00:00
|
|
|
"formset": formset,
|
|
|
|
})
|
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
As you can see, the view logic of a model formset isn't drastically different
|
|
|
|
than that of a "normal" formset. The only difference is that we call
|
|
|
|
``formset.save()`` to save the data into the database. (This was described
|
|
|
|
above, in :ref:`saving-objects-in-the-formset`.)
|
2008-09-02 17:57:02 +00:00
|
|
|
|
2013-07-08 12:29:28 +00:00
|
|
|
.. _model-formsets-overriding-clean:
|
|
|
|
|
|
|
|
Overriding ``clean()`` on a ``ModelFormSet``
|
2009-05-07 12:17:52 +00:00
|
|
|
--------------------------------------------
|
|
|
|
|
|
|
|
Just like with ``ModelForms``, by default the ``clean()`` method of a
|
2013-07-08 12:29:28 +00:00
|
|
|
``ModelFormSet`` will validate that none of the items in the formset violate
|
2009-05-17 16:12:05 +00:00
|
|
|
the unique constraints on your model (either ``unique``, ``unique_together`` or
|
2011-08-13 11:58:19 +00:00
|
|
|
``unique_for_date|month|year``). If you want to override the ``clean()`` method
|
2013-07-08 12:29:28 +00:00
|
|
|
on a ``ModelFormSet`` and maintain this validation, you must call the parent
|
2009-06-18 13:33:52 +00:00
|
|
|
class's ``clean`` method::
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
from django.forms.models import BaseModelFormSet
|
|
|
|
|
2009-05-17 16:12:05 +00:00
|
|
|
class MyModelFormSet(BaseModelFormSet):
|
|
|
|
def clean(self):
|
|
|
|
super(MyModelFormSet, self).clean()
|
|
|
|
# example custom validation across forms in the formset:
|
|
|
|
for form in self.forms:
|
|
|
|
# your custom formset validation
|
2013-05-19 09:15:35 +00:00
|
|
|
pass
|
2009-05-07 12:17:52 +00:00
|
|
|
|
2008-12-09 00:31:17 +00:00
|
|
|
Using a custom queryset
|
2009-05-17 16:12:05 +00:00
|
|
|
-----------------------
|
2008-12-09 00:31:17 +00:00
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
As stated earlier, you can override the default queryset used by the model
|
|
|
|
formset::
|
2008-12-09 00:31:17 +00:00
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
from django.forms.models import modelformset_factory
|
|
|
|
from django.shortcuts import render_to_response
|
|
|
|
from myapp.models import Author
|
|
|
|
|
2008-12-09 00:31:17 +00:00
|
|
|
def manage_authors(request):
|
|
|
|
AuthorFormSet = modelformset_factory(Author)
|
|
|
|
if request.method == "POST":
|
|
|
|
formset = AuthorFormSet(request.POST, request.FILES,
|
|
|
|
queryset=Author.objects.filter(name__startswith='O'))
|
|
|
|
if formset.is_valid():
|
|
|
|
formset.save()
|
2008-12-09 04:17:14 +00:00
|
|
|
# Do something.
|
2008-12-09 00:31:17 +00:00
|
|
|
else:
|
|
|
|
formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O'))
|
|
|
|
return render_to_response("manage_authors.html", {
|
|
|
|
"formset": formset,
|
|
|
|
})
|
2008-07-18 23:54:34 +00:00
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
Note that we pass the ``queryset`` argument in both the ``POST`` and ``GET``
|
|
|
|
cases in this example.
|
2008-12-09 00:31:17 +00:00
|
|
|
|
|
|
|
Using the formset in the template
|
2009-05-17 16:12:05 +00:00
|
|
|
---------------------------------
|
|
|
|
|
|
|
|
.. highlight:: html+django
|
2008-12-09 00:31:17 +00:00
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
There are three ways to render a formset in a Django template.
|
|
|
|
|
|
|
|
First, you can let the formset do most of the work::
|
2008-12-09 00:31:17 +00:00
|
|
|
|
2010-01-04 21:55:52 +00:00
|
|
|
<form method="post" action="">
|
2008-12-09 00:31:17 +00:00
|
|
|
{{ formset }}
|
|
|
|
</form>
|
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
Second, you can manually render the formset, but let the form deal with
|
|
|
|
itself::
|
2008-12-09 00:31:17 +00:00
|
|
|
|
2010-01-04 21:55:52 +00:00
|
|
|
<form method="post" action="">
|
2008-12-09 00:31:17 +00:00
|
|
|
{{ formset.management_form }}
|
2010-12-19 13:41:43 +00:00
|
|
|
{% for form in formset %}
|
2008-12-09 00:31:17 +00:00
|
|
|
{{ form }}
|
|
|
|
{% endfor %}
|
|
|
|
</form>
|
|
|
|
|
|
|
|
When you manually render the forms yourself, be sure to render the management
|
2008-12-23 00:01:09 +00:00
|
|
|
form as shown above. See the :ref:`management form documentation
|
|
|
|
<understanding-the-managementform>`.
|
2008-12-09 00:31:17 +00:00
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
Third, you can manually render each field::
|
2008-12-09 00:31:17 +00:00
|
|
|
|
2010-01-04 21:55:52 +00:00
|
|
|
<form method="post" action="">
|
2008-12-09 00:31:17 +00:00
|
|
|
{{ formset.management_form }}
|
2010-12-19 13:41:43 +00:00
|
|
|
{% for form in formset %}
|
2008-12-23 05:20:49 +00:00
|
|
|
{% for field in form %}
|
2012-06-08 13:32:35 +00:00
|
|
|
{{ field.label_tag }} {{ field }}
|
2008-12-09 00:31:17 +00:00
|
|
|
{% endfor %}
|
|
|
|
{% endfor %}
|
|
|
|
</form>
|
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
If you opt to use this third method and you don't iterate over the fields with
|
|
|
|
a ``{% for %}`` loop, you'll need to render the primary key field. For example,
|
|
|
|
if you were rendering the ``name`` and ``age`` fields of a model::
|
2008-12-09 00:31:17 +00:00
|
|
|
|
2010-01-04 21:55:52 +00:00
|
|
|
<form method="post" action="">
|
2008-12-09 00:31:17 +00:00
|
|
|
{{ formset.management_form }}
|
2010-12-19 13:41:43 +00:00
|
|
|
{% for form in formset %}
|
2008-12-09 00:31:17 +00:00
|
|
|
{{ form.id }}
|
|
|
|
<ul>
|
|
|
|
<li>{{ form.name }}</li>
|
|
|
|
<li>{{ form.age }}</li>
|
|
|
|
</ul>
|
|
|
|
{% endfor %}
|
|
|
|
</form>
|
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
Notice how we need to explicitly render ``{{ form.id }}``. This ensures that
|
|
|
|
the model formset, in the ``POST`` case, will work correctly. (This example
|
|
|
|
assumes a primary key named ``id``. If you've explicitly defined your own
|
|
|
|
primary key that isn't called ``id``, make sure it gets rendered.)
|
2008-12-09 00:31:17 +00:00
|
|
|
|
2009-05-17 16:12:05 +00:00
|
|
|
.. highlight:: python
|
|
|
|
|
2013-01-22 11:46:22 +00:00
|
|
|
.. _inline-formsets:
|
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
Inline formsets
|
2008-12-09 00:31:17 +00:00
|
|
|
===============
|
|
|
|
|
2013-07-08 12:29:28 +00:00
|
|
|
.. class:: models.BaseInlineFormSet
|
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
Inline formsets is a small abstraction layer on top of model formsets. These
|
|
|
|
simplify the case of working with related objects via a foreign key. Suppose
|
2008-12-09 00:31:17 +00:00
|
|
|
you have these two models::
|
2008-09-02 17:57:18 +00:00
|
|
|
|
2013-05-19 09:15:35 +00:00
|
|
|
from django.db import models
|
|
|
|
|
2008-09-02 17:57:18 +00:00
|
|
|
class Author(models.Model):
|
|
|
|
name = models.CharField(max_length=100)
|
2008-12-09 04:17:14 +00:00
|
|
|
|
2008-09-02 17:57:18 +00:00
|
|
|
class Book(models.Model):
|
|
|
|
author = models.ForeignKey(Author)
|
|
|
|
title = models.CharField(max_length=100)
|
|
|
|
|
|
|
|
If you want to create a formset that allows you to edit books belonging to
|
2008-12-09 04:17:14 +00:00
|
|
|
a particular author, you could do this::
|
2008-07-18 23:54:34 +00:00
|
|
|
|
2008-07-21 16:56:52 +00:00
|
|
|
>>> from django.forms.models import inlineformset_factory
|
2008-07-18 23:54:34 +00:00
|
|
|
>>> BookFormSet = inlineformset_factory(Author, Book)
|
2008-12-09 04:17:14 +00:00
|
|
|
>>> author = Author.objects.get(name=u'Mike Royko')
|
2008-09-01 19:08:08 +00:00
|
|
|
>>> formset = BookFormSet(instance=author)
|
2008-09-02 17:57:18 +00:00
|
|
|
|
2008-09-12 16:52:28 +00:00
|
|
|
.. note::
|
2013-01-11 10:59:17 +00:00
|
|
|
|
2013-01-22 11:46:22 +00:00
|
|
|
:func:`~django.forms.models.inlineformset_factory` uses
|
2013-01-11 10:59:17 +00:00
|
|
|
:func:`~django.forms.models.modelformset_factory` and marks
|
2008-09-12 16:52:28 +00:00
|
|
|
``can_delete=True``.
|
|
|
|
|
2011-06-17 15:39:28 +00:00
|
|
|
.. seealso::
|
|
|
|
|
|
|
|
:ref:`Manually rendered can_delete and can_order <manually-rendered-can-delete-and-can-order>`.
|
|
|
|
|
2013-07-08 12:29:28 +00:00
|
|
|
Overriding ``clean()`` on an ``InlineFormSet``
|
|
|
|
----------------------------------------------
|
|
|
|
|
|
|
|
See :ref:`model-formsets-overriding-clean`, but subclass
|
|
|
|
:class:`~models.BaseInlineFormSet` rather than
|
|
|
|
:class:`~models.BaseModelFormSet`.
|
|
|
|
|
2008-09-06 00:09:17 +00:00
|
|
|
More than one foreign key to the same model
|
2008-12-09 00:31:17 +00:00
|
|
|
-------------------------------------------
|
2008-09-02 17:57:18 +00:00
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
If your model contains more than one foreign key to the same model, you'll
|
|
|
|
need to resolve the ambiguity manually using ``fk_name``. For example, consider
|
|
|
|
the following model::
|
2008-09-02 17:57:18 +00:00
|
|
|
|
|
|
|
class Friendship(models.Model):
|
|
|
|
from_friend = models.ForeignKey(Friend)
|
|
|
|
to_friend = models.ForeignKey(Friend)
|
|
|
|
length_in_months = models.IntegerField()
|
|
|
|
|
2013-01-22 11:46:22 +00:00
|
|
|
To resolve this, you can use ``fk_name`` to
|
|
|
|
:func:`~django.forms.models.inlineformset_factory`::
|
2008-09-02 17:57:18 +00:00
|
|
|
|
2009-05-17 16:12:05 +00:00
|
|
|
>>> FriendshipFormSet = inlineformset_factory(Friend, Friendship, fk_name="from_friend")
|
2008-12-09 00:31:17 +00:00
|
|
|
|
|
|
|
Using an inline formset in a view
|
|
|
|
---------------------------------
|
|
|
|
|
|
|
|
You may want to provide a view that allows a user to edit the related objects
|
2008-12-09 04:17:14 +00:00
|
|
|
of a model. Here's how you can do that::
|
2008-12-09 00:31:17 +00:00
|
|
|
|
|
|
|
def manage_books(request, author_id):
|
|
|
|
author = Author.objects.get(pk=author_id)
|
|
|
|
BookInlineFormSet = inlineformset_factory(Author, Book)
|
|
|
|
if request.method == "POST":
|
|
|
|
formset = BookInlineFormSet(request.POST, request.FILES, instance=author)
|
|
|
|
if formset.is_valid():
|
|
|
|
formset.save()
|
2012-06-23 16:44:40 +00:00
|
|
|
# Do something. Should generally end with a redirect. For example:
|
|
|
|
return HttpResponseRedirect(author.get_absolute_url())
|
2008-12-09 00:31:17 +00:00
|
|
|
else:
|
|
|
|
formset = BookInlineFormSet(instance=author)
|
|
|
|
return render_to_response("manage_books.html", {
|
|
|
|
"formset": formset,
|
|
|
|
})
|
|
|
|
|
2008-12-09 04:17:14 +00:00
|
|
|
Notice how we pass ``instance`` in both the ``POST`` and ``GET`` cases.
|
2013-01-23 20:11:46 +00:00
|
|
|
|
|
|
|
Specifying widgets to use in the inline form
|
|
|
|
--------------------------------------------
|
|
|
|
|
|
|
|
.. versionadded:: 1.6
|
|
|
|
|
|
|
|
``inlineformset_factory`` uses ``modelformset_factory`` and passes most
|
|
|
|
of its arguments to ``modelformset_factory``. This means you can use
|
|
|
|
the ``widgets`` parameter in much the same way as passing it to
|
|
|
|
``modelformset_factory``. See `Specifying widgets to use in the form with widgets`_ above.
|