modelforms.txt 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932
  1. ==========================
  2. Creating forms from models
  3. ==========================
  4. .. module:: django.forms.models
  5. :synopsis: ModelForm and ModelFormset.
  6. .. currentmodule:: django.forms
  7. ``ModelForm``
  8. =============
  9. .. class:: ModelForm
  10. If you're building a database-driven app, chances are you'll have forms that
  11. map closely to Django models. For instance, you might have a ``BlogComment``
  12. model, and you want to create a form that lets people submit comments. In this
  13. case, it would be redundant to define the field types in your form, because
  14. you've already defined the fields in your model.
  15. For this reason, Django provides a helper class that let you create a ``Form``
  16. class from a Django model.
  17. For example::
  18. >>> from django.forms import ModelForm
  19. # Create the form class.
  20. >>> class ArticleForm(ModelForm):
  21. ... class Meta:
  22. ... model = Article
  23. # Creating a form to add an article.
  24. >>> form = ArticleForm()
  25. # Creating a form to change an existing article.
  26. >>> article = Article.objects.get(pk=1)
  27. >>> form = ArticleForm(instance=article)
  28. Field types
  29. -----------
  30. The generated ``Form`` class will have a form field for every model field. Each
  31. model field has a corresponding default form field. For example, a
  32. ``CharField`` on a model is represented as a ``CharField`` on a form. A
  33. model ``ManyToManyField`` is represented as a ``MultipleChoiceField``. Here is
  34. the full list of conversions:
  35. =============================== ========================================
  36. Model field Form field
  37. =============================== ========================================
  38. ``AutoField`` Not represented in the form
  39. ``BigIntegerField`` ``IntegerField`` with ``min_value`` set
  40. to -9223372036854775808 and ``max_value``
  41. set to 9223372036854775807.
  42. ``BooleanField`` ``BooleanField``
  43. ``CharField`` ``CharField`` with ``max_length`` set to
  44. the model field's ``max_length``
  45. ``CommaSeparatedIntegerField`` ``CharField``
  46. ``DateField`` ``DateField``
  47. ``DateTimeField`` ``DateTimeField``
  48. ``DecimalField`` ``DecimalField``
  49. ``EmailField`` ``EmailField``
  50. ``FileField`` ``FileField``
  51. ``FilePathField`` ``CharField``
  52. ``FloatField`` ``FloatField``
  53. ``ForeignKey`` ``ModelChoiceField`` (see below)
  54. ``ImageField`` ``ImageField``
  55. ``IntegerField`` ``IntegerField``
  56. ``IPAddressField`` ``IPAddressField``
  57. ``GenericIPAddressField`` ``GenericIPAddressField``
  58. ``ManyToManyField`` ``ModelMultipleChoiceField`` (see
  59. below)
  60. ``NullBooleanField`` ``CharField``
  61. ``PositiveIntegerField`` ``IntegerField``
  62. ``PositiveSmallIntegerField`` ``IntegerField``
  63. ``SlugField`` ``SlugField``
  64. ``SmallIntegerField`` ``IntegerField``
  65. ``TextField`` ``CharField`` with
  66. ``widget=forms.Textarea``
  67. ``TimeField`` ``TimeField``
  68. ``URLField`` ``URLField``
  69. =============================== ========================================
  70. As you might expect, the ``ForeignKey`` and ``ManyToManyField`` model field
  71. types are special cases:
  72. * ``ForeignKey`` is represented by ``django.forms.ModelChoiceField``,
  73. which is a ``ChoiceField`` whose choices are a model ``QuerySet``.
  74. * ``ManyToManyField`` is represented by
  75. ``django.forms.ModelMultipleChoiceField``, which is a
  76. ``MultipleChoiceField`` whose choices are a model ``QuerySet``.
  77. In addition, each generated form field has attributes set as follows:
  78. * If the model field has ``blank=True``, then ``required`` is set to
  79. ``False`` on the form field. Otherwise, ``required=True``.
  80. * The form field's ``label`` is set to the ``verbose_name`` of the model
  81. field, with the first character capitalized.
  82. * The form field's ``help_text`` is set to the ``help_text`` of the model
  83. field.
  84. * If the model field has ``choices`` set, then the form field's ``widget``
  85. will be set to ``Select``, with choices coming from the model field's
  86. ``choices``. The choices will normally include the blank choice which is
  87. selected by default. If the field is required, this forces the user to
  88. make a selection. The blank choice will not be included if the model
  89. field has ``blank=False`` and an explicit ``default`` value (the
  90. ``default`` value will be initially selected instead).
  91. Finally, note that you can override the form field used for a given model
  92. field. See `Overriding the default field types or widgets`_ below.
  93. A full example
  94. --------------
  95. Consider this set of models::
  96. from django.db import models
  97. from django.forms import ModelForm
  98. TITLE_CHOICES = (
  99. ('MR', 'Mr.'),
  100. ('MRS', 'Mrs.'),
  101. ('MS', 'Ms.'),
  102. )
  103. class Author(models.Model):
  104. name = models.CharField(max_length=100)
  105. title = models.CharField(max_length=3, choices=TITLE_CHOICES)
  106. birth_date = models.DateField(blank=True, null=True)
  107. def __unicode__(self):
  108. return self.name
  109. class Book(models.Model):
  110. name = models.CharField(max_length=100)
  111. authors = models.ManyToManyField(Author)
  112. class AuthorForm(ModelForm):
  113. class Meta:
  114. model = Author
  115. class BookForm(ModelForm):
  116. class Meta:
  117. model = Book
  118. With these models, the ``ModelForm`` subclasses above would be roughly
  119. equivalent to this (the only difference being the ``save()`` method, which
  120. we'll discuss in a moment.)::
  121. from django import forms
  122. class AuthorForm(forms.Form):
  123. name = forms.CharField(max_length=100)
  124. title = forms.CharField(max_length=3,
  125. widget=forms.Select(choices=TITLE_CHOICES))
  126. birth_date = forms.DateField(required=False)
  127. class BookForm(forms.Form):
  128. name = forms.CharField(max_length=100)
  129. authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all())
  130. .. _modelform-is-valid-and-errors:
  131. The ``is_valid()`` method and ``errors``
  132. ----------------------------------------
  133. The first time you call ``is_valid()`` or access the ``errors`` attribute of a
  134. ``ModelForm`` triggers :ref:`form validation <form-and-field-validation>` as
  135. well as :ref:`model validation <validating-objects>`. This has the side-effect
  136. of cleaning the model you pass to the ``ModelForm`` constructor. For instance,
  137. calling ``is_valid()`` on your form will convert any date fields on your model
  138. to actual date objects. If form validation fails, only some of the updates
  139. may be applied. For this reason, you'll probably want to avoid reusing the
  140. model instance passed to the form, especially if validation fails.
  141. The ``save()`` method
  142. ---------------------
  143. Every form produced by ``ModelForm`` also has a ``save()``
  144. method. This method creates and saves a database object from the data
  145. bound to the form. A subclass of ``ModelForm`` can accept an existing
  146. model instance as the keyword argument ``instance``; if this is
  147. supplied, ``save()`` will update that instance. If it's not supplied,
  148. ``save()`` will create a new instance of the specified model:
  149. .. code-block:: python
  150. # Create a form instance from POST data.
  151. >>> f = ArticleForm(request.POST)
  152. # Save a new Article object from the form's data.
  153. >>> new_article = f.save()
  154. # Create a form to edit an existing Article.
  155. >>> a = Article.objects.get(pk=1)
  156. >>> f = ArticleForm(instance=a)
  157. >>> f.save()
  158. # Create a form to edit an existing Article, but use
  159. # POST data to populate the form.
  160. >>> a = Article.objects.get(pk=1)
  161. >>> f = ArticleForm(request.POST, instance=a)
  162. >>> f.save()
  163. Note that if the form :ref:`hasn't been validated
  164. <modelform-is-valid-and-errors>`, calling ``save()`` will do so by checking
  165. ``form.errors``. A ``ValueError`` will be raised if the data in the form
  166. doesn't validate -- i.e., if ``form.errors`` evaluates to ``True``.
  167. This ``save()`` method accepts an optional ``commit`` keyword argument, which
  168. accepts either ``True`` or ``False``. If you call ``save()`` with
  169. ``commit=False``, then it will return an object that hasn't yet been saved to
  170. the database. In this case, it's up to you to call ``save()`` on the resulting
  171. model instance. This is useful if you want to do custom processing on the
  172. object before saving it, or if you want to use one of the specialized
  173. :ref:`model saving options <ref-models-force-insert>`. ``commit`` is ``True``
  174. by default.
  175. Another side effect of using ``commit=False`` is seen when your model has
  176. a many-to-many relation with another model. If your model has a many-to-many
  177. relation and you specify ``commit=False`` when you save a form, Django cannot
  178. immediately save the form data for the many-to-many relation. This is because
  179. it isn't possible to save many-to-many data for an instance until the instance
  180. exists in the database.
  181. To work around this problem, every time you save a form using ``commit=False``,
  182. Django adds a ``save_m2m()`` method to your ``ModelForm`` subclass. After
  183. you've manually saved the instance produced by the form, you can invoke
  184. ``save_m2m()`` to save the many-to-many form data. For example::
  185. # Create a form instance with POST data.
  186. >>> f = AuthorForm(request.POST)
  187. # Create, but don't save the new author instance.
  188. >>> new_author = f.save(commit=False)
  189. # Modify the author in some way.
  190. >>> new_author.some_field = 'some_value'
  191. # Save the new instance.
  192. >>> new_author.save()
  193. # Now, save the many-to-many data for the form.
  194. >>> f.save_m2m()
  195. Calling ``save_m2m()`` is only required if you use ``save(commit=False)``.
  196. When you use a simple ``save()`` on a form, all data -- including
  197. many-to-many data -- is saved without the need for any additional method calls.
  198. For example::
  199. # Create a form instance with POST data.
  200. >>> a = Author()
  201. >>> f = AuthorForm(request.POST, instance=a)
  202. # Create and save the new author instance. There's no need to do anything else.
  203. >>> new_author = f.save()
  204. Other than the ``save()`` and ``save_m2m()`` methods, a ``ModelForm`` works
  205. exactly the same way as any other ``forms`` form. For example, the
  206. ``is_valid()`` method is used to check for validity, the ``is_multipart()``
  207. method is used to determine whether a form requires multipart file upload (and
  208. hence whether ``request.FILES`` must be passed to the form), etc. See
  209. :ref:`binding-uploaded-files` for more information.
  210. Using a subset of fields on the form
  211. ------------------------------------
  212. In some cases, you may not want all the model fields to appear on the generated
  213. form. There are three ways of telling ``ModelForm`` to use only a subset of the
  214. model fields:
  215. 1. Set ``editable=False`` on the model field. As a result, *any* form
  216. created from the model via ``ModelForm`` will not include that
  217. field.
  218. 2. Use the ``fields`` attribute of the ``ModelForm``'s inner ``Meta``
  219. class. This attribute, if given, should be a list of field names
  220. to include in the form. The order in which the fields names are specified
  221. in that list is respected when the form renders them.
  222. 3. Use the ``exclude`` attribute of the ``ModelForm``'s inner ``Meta``
  223. class. This attribute, if given, should be a list of field names
  224. to exclude from the form.
  225. For example, if you want a form for the ``Author`` model (defined
  226. above) that includes only the ``name`` and ``birth_date`` fields, you would
  227. specify ``fields`` or ``exclude`` like this::
  228. class PartialAuthorForm(ModelForm):
  229. class Meta:
  230. model = Author
  231. fields = ('name', 'birth_date')
  232. class PartialAuthorForm(ModelForm):
  233. class Meta:
  234. model = Author
  235. exclude = ('title',)
  236. Since the Author model has only 3 fields, 'name', 'title', and
  237. 'birth_date', the forms above will contain exactly the same fields.
  238. .. note::
  239. If you specify ``fields`` or ``exclude`` when creating a form with
  240. ``ModelForm``, then the fields that are not in the resulting form
  241. will not be set by the form's ``save()`` method. Also, if you
  242. manually add the excluded fields back to the form, they will not
  243. be initialized from the model instance.
  244. Django will prevent any attempt to save an incomplete model, so if
  245. the model does not allow the missing fields to be empty, and does
  246. not provide a default value for the missing fields, any attempt to
  247. ``save()`` a ``ModelForm`` with missing fields will fail. To
  248. avoid this failure, you must instantiate your model with initial
  249. values for the missing, but required fields::
  250. author = Author(title='Mr')
  251. form = PartialAuthorForm(request.POST, instance=author)
  252. form.save()
  253. Alternatively, you can use ``save(commit=False)`` and manually set
  254. any extra required fields::
  255. form = PartialAuthorForm(request.POST)
  256. author = form.save(commit=False)
  257. author.title = 'Mr'
  258. author.save()
  259. See the `section on saving forms`_ for more details on using
  260. ``save(commit=False)``.
  261. .. _section on saving forms: `The save() method`_
  262. Overriding the default field types or widgets
  263. ---------------------------------------------
  264. The default field types, as described in the `Field types`_ table above, are
  265. sensible defaults. If you have a ``DateField`` in your model, chances are you'd
  266. want that to be represented as a ``DateField`` in your form. But
  267. ``ModelForm`` gives you the flexibility of changing the form field type and
  268. widget for a given model field.
  269. To specify a custom widget for a field, use the ``widgets`` attribute of the
  270. inner ``Meta`` class. This should be a dictionary mapping field names to widget
  271. classes or instances.
  272. For example, if you want the a ``CharField`` for the ``name``
  273. attribute of ``Author`` to be represented by a ``<textarea>`` instead
  274. of its default ``<input type="text">``, you can override the field's
  275. widget::
  276. from django.forms import ModelForm, Textarea
  277. class AuthorForm(ModelForm):
  278. class Meta:
  279. model = Author
  280. fields = ('name', 'title', 'birth_date')
  281. widgets = {
  282. 'name': Textarea(attrs={'cols': 80, 'rows': 20}),
  283. }
  284. The ``widgets`` dictionary accepts either widget instances (e.g.,
  285. ``Textarea(...)``) or classes (e.g., ``Textarea``).
  286. If you want to further customize a field -- including its type, label, etc. --
  287. you can do this by declaratively specifying fields like you would in a regular
  288. ``Form``. Declared fields will override the default ones generated by using the
  289. ``model`` attribute.
  290. For example, if you wanted to use ``MyDateFormField`` for the ``pub_date``
  291. field, you could do the following::
  292. class ArticleForm(ModelForm):
  293. pub_date = MyDateFormField()
  294. class Meta:
  295. model = Article
  296. If you want to override a field's default label, then specify the ``label``
  297. parameter when declaring the form field::
  298. >>> class ArticleForm(ModelForm):
  299. ... pub_date = DateField(label='Publication date')
  300. ...
  301. ... class Meta:
  302. ... model = Article
  303. .. note::
  304. If you explicitly instantiate a form field like this, Django assumes that you
  305. want to completely define its behavior; therefore, default attributes (such as
  306. ``max_length`` or ``required``) are not drawn from the corresponding model. If
  307. you want to maintain the behavior specified in the model, you must set the
  308. relevant arguments explicitly when declaring the form field.
  309. For example, if the ``Article`` model looks like this::
  310. class Article(models.Model):
  311. headline = models.CharField(max_length=200, null=True, blank=True,
  312. help_text="Use puns liberally")
  313. content = models.TextField()
  314. and you want to do some custom validation for ``headline``, while keeping
  315. the ``blank`` and ``help_text`` values as specified, you might define
  316. ``ArticleForm`` like this::
  317. class ArticleForm(ModelForm):
  318. headline = MyFormField(max_length=200, required=False,
  319. help_text="Use puns liberally")
  320. class Meta:
  321. model = Article
  322. You must ensure that the type of the form field can be used to set the
  323. contents of the corresponding model field. When they are not compatible,
  324. you will get a ``ValueError`` as no implicit conversion takes place.
  325. See the :doc:`form field documentation </ref/forms/fields>` for more information
  326. on fields and their arguments.
  327. Changing the order of fields
  328. ----------------------------
  329. By default, a ``ModelForm`` will render fields in the same order that they are
  330. defined on the model, with ``ManyToManyField`` instances appearing last. If
  331. you want to change the order in which fields are rendered, you can use the
  332. ``fields`` attribute on the ``Meta`` class.
  333. The ``fields`` attribute defines the subset of model fields that will be
  334. rendered, and the order in which they will be rendered. For example given this
  335. model::
  336. class Book(models.Model):
  337. author = models.ForeignKey(Author)
  338. title = models.CharField(max_length=100)
  339. the ``author`` field would be rendered first. If we wanted the title field
  340. to be rendered first, we could specify the following ``ModelForm``::
  341. >>> class BookForm(ModelForm):
  342. ... class Meta:
  343. ... model = Book
  344. ... fields = ('title', 'author')
  345. .. _overriding-modelform-clean-method:
  346. Overriding the clean() method
  347. -----------------------------
  348. You can override the ``clean()`` method on a model form to provide additional
  349. validation in the same way you can on a normal form.
  350. In this regard, model forms have two specific characteristics when compared to
  351. forms:
  352. By default the ``clean()`` method validates the uniqueness of fields that are
  353. marked as ``unique``, ``unique_together`` or ``unique_for_date|month|year`` on
  354. the model. Therefore, if you would like to override the ``clean()`` method and
  355. maintain the default validation, you must call the parent class's ``clean()``
  356. method.
  357. Also, a model form instance bound to a model object will contain a
  358. ``self.instance`` attribute that gives model form methods access to that
  359. specific model instance.
  360. Form inheritance
  361. ----------------
  362. As with basic forms, you can extend and reuse ``ModelForms`` by inheriting
  363. them. This is useful if you need to declare extra fields or extra methods on a
  364. parent class for use in a number of forms derived from models. For example,
  365. using the previous ``ArticleForm`` class::
  366. >>> class EnhancedArticleForm(ArticleForm):
  367. ... def clean_pub_date(self):
  368. ... ...
  369. This creates a form that behaves identically to ``ArticleForm``, except there's
  370. some extra validation and cleaning for the ``pub_date`` field.
  371. You can also subclass the parent's ``Meta`` inner class if you want to change
  372. the ``Meta.fields`` or ``Meta.excludes`` lists::
  373. >>> class RestrictedArticleForm(EnhancedArticleForm):
  374. ... class Meta(ArticleForm.Meta):
  375. ... exclude = ('body',)
  376. This adds the extra method from the ``EnhancedArticleForm`` and modifies
  377. the original ``ArticleForm.Meta`` to remove one field.
  378. There are a couple of things to note, however.
  379. * Normal Python name resolution rules apply. If you have multiple base
  380. classes that declare a ``Meta`` inner class, only the first one will be
  381. used. This means the child's ``Meta``, if it exists, otherwise the
  382. ``Meta`` of the first parent, etc.
  383. * For technical reasons, a subclass cannot inherit from both a ``ModelForm``
  384. and a ``Form`` simultaneously.
  385. Chances are these notes won't affect you unless you're trying to do something
  386. tricky with subclassing.
  387. Interaction with model validation
  388. ---------------------------------
  389. As part of its validation process, ``ModelForm`` will call the ``clean()``
  390. method of each field on your model that has a corresponding field on your form.
  391. If you have excluded any model fields, validation will not be run on those
  392. fields. See the :doc:`form validation </ref/forms/validation>` documentation
  393. for more on how field cleaning and validation work. Also, your model's
  394. ``clean()`` method will be called before any uniqueness checks are made. See
  395. :ref:`Validating objects <validating-objects>` for more information on the
  396. model's ``clean()`` hook.
  397. .. _modelforms-factory:
  398. ModelForm factory function
  399. --------------------------
  400. You can create forms from a given model using the standalone function
  401. :func:`~django.forms.models.modelform_factory`, instead of using a class
  402. definition. This may be more convenient if you do not have many customizations
  403. to make::
  404. >>> from django.forms.models import modelform_factory
  405. >>> BookForm = modelform_factory(Book)
  406. This can also be used to make simple modifications to existing forms, for
  407. example by specifying which fields should be displayed::
  408. >>> Form = modelform_factory(Book, form=BookForm, fields=("author",))
  409. ... or which fields should be excluded::
  410. >>> Form = modelform_factory(Book, form=BookForm, exclude=("title",))
  411. You can also specify the widgets to be used for a given field::
  412. >>> from django.forms import Textarea
  413. >>> Form = modelform_factory(Book, form=BookForm, widgets={"title": Textarea()})
  414. .. _model-formsets:
  415. Model formsets
  416. ==============
  417. .. class:: models.BaseModelFormSet
  418. Like :doc:`regular formsets </topics/forms/formsets>`, Django provides a couple
  419. of enhanced formset classes that make it easy to work with Django models. Let's
  420. reuse the ``Author`` model from above::
  421. >>> from django.forms.models import modelformset_factory
  422. >>> AuthorFormSet = modelformset_factory(Author)
  423. This will create a formset that is capable of working with the data associated
  424. with the ``Author`` model. It works just like a regular formset::
  425. >>> formset = AuthorFormSet()
  426. >>> print(formset)
  427. <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" />
  428. <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>
  429. <tr><th><label for="id_form-0-title">Title:</label></th><td><select name="form-0-title" id="id_form-0-title">
  430. <option value="" selected="selected">---------</option>
  431. <option value="MR">Mr.</option>
  432. <option value="MRS">Mrs.</option>
  433. <option value="MS">Ms.</option>
  434. </select></td></tr>
  435. <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>
  436. .. note::
  437. :func:`~django.forms.models.modelformset_factory` uses ``formset_factory``
  438. to generate formsets. This means that a model formset is just an extension
  439. of a basic formset that knows how to interact with a particular model.
  440. Changing the queryset
  441. ---------------------
  442. By default, when you create a formset from a model, the formset will use a
  443. queryset that includes all objects in the model (e.g.,
  444. ``Author.objects.all()``). You can override this behavior by using the
  445. ``queryset`` argument::
  446. >>> formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O'))
  447. Alternatively, you can create a subclass that sets ``self.queryset`` in
  448. ``__init__``::
  449. from django.forms.models import BaseModelFormSet
  450. class BaseAuthorFormSet(BaseModelFormSet):
  451. def __init__(self, *args, **kwargs):
  452. super(BaseAuthorFormSet, self).__init__(*args, **kwargs)
  453. self.queryset = Author.objects.filter(name__startswith='O')
  454. Then, pass your ``BaseAuthorFormSet`` class to the factory function::
  455. >>> AuthorFormSet = modelformset_factory(Author, formset=BaseAuthorFormSet)
  456. If you want to return a formset that doesn't include *any* pre-existing
  457. instances of the model, you can specify an empty QuerySet::
  458. >>> AuthorFormSet(queryset=Author.objects.none())
  459. Controlling which fields are used with ``fields`` and ``exclude``
  460. -----------------------------------------------------------------
  461. By default, a model formset uses all fields in the model that are not marked
  462. with ``editable=False``. However, this can be overridden at the formset level::
  463. >>> AuthorFormSet = modelformset_factory(Author, fields=('name', 'title'))
  464. Using ``fields`` restricts the formset to use only the given fields.
  465. Alternatively, you can take an "opt-out" approach, specifying which fields to
  466. exclude::
  467. >>> AuthorFormSet = modelformset_factory(Author, exclude=('birth_date',))
  468. Providing initial values
  469. ------------------------
  470. As with regular formsets, it's possible to :ref:`specify initial data
  471. <formsets-initial-data>` for forms in the formset by specifying an ``initial``
  472. parameter when instantiating the model formset class returned by
  473. :func:`~django.forms.models.modelformset_factory`. However, with model
  474. formsets, the initial values only apply to extra forms, those that aren't bound
  475. to an existing object instance.
  476. .. _saving-objects-in-the-formset:
  477. Saving objects in the formset
  478. -----------------------------
  479. As with a ``ModelForm``, you can save the data as a model object. This is done
  480. with the formset's ``save()`` method::
  481. # Create a formset instance with POST data.
  482. >>> formset = AuthorFormSet(request.POST)
  483. # Assuming all is valid, save the data.
  484. >>> instances = formset.save()
  485. The ``save()`` method returns the instances that have been saved to the
  486. database. If a given instance's data didn't change in the bound data, the
  487. instance won't be saved to the database and won't be included in the return
  488. value (``instances``, in the above example).
  489. When fields are missing from the form (for example because they have
  490. been excluded), these fields will not be set by the ``save()``
  491. method. You can find more information about this restriction, which
  492. also holds for regular ``ModelForms``, in `Using a subset of fields on
  493. the form`_.
  494. Pass ``commit=False`` to return the unsaved model instances::
  495. # don't save to the database
  496. >>> instances = formset.save(commit=False)
  497. >>> for instance in instances:
  498. ... # do something with instance
  499. ... instance.save()
  500. This gives you the ability to attach data to the instances before saving them
  501. to the database. If your formset contains a ``ManyToManyField``, you'll also
  502. need to call ``formset.save_m2m()`` to ensure the many-to-many relationships
  503. are saved properly.
  504. .. _model-formsets-max-num:
  505. Limiting the number of editable objects
  506. ---------------------------------------
  507. As with regular formsets, you can use the ``max_num`` and ``extra`` parameters
  508. to :func:`~django.forms.models.modelformset_factory` to limit the number of
  509. extra forms displayed.
  510. ``max_num`` does not prevent existing objects from being displayed::
  511. >>> Author.objects.order_by('name')
  512. [<Author: Charles Baudelaire>, <Author: Paul Verlaine>, <Author: Walt Whitman>]
  513. >>> AuthorFormSet = modelformset_factory(Author, max_num=1)
  514. >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
  515. >>> [x.name for x in formset.get_queryset()]
  516. [u'Charles Baudelaire', u'Paul Verlaine', u'Walt Whitman']
  517. If the value of ``max_num`` is greater than the number of existing related
  518. objects, up to ``extra`` additional blank forms will be added to the formset,
  519. so long as the total number of forms does not exceed ``max_num``::
  520. >>> AuthorFormSet = modelformset_factory(Author, max_num=4, extra=2)
  521. >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
  522. >>> for form in formset:
  523. ... print(form.as_table())
  524. <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>
  525. <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>
  526. <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>
  527. <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>
  528. A ``max_num`` value of ``None`` (the default) puts no limit on the number of
  529. forms displayed.
  530. Using a model formset in a view
  531. -------------------------------
  532. Model formsets are very similar to formsets. Let's say we want to present a
  533. formset to edit ``Author`` model instances::
  534. def manage_authors(request):
  535. AuthorFormSet = modelformset_factory(Author)
  536. if request.method == 'POST':
  537. formset = AuthorFormSet(request.POST, request.FILES)
  538. if formset.is_valid():
  539. formset.save()
  540. # do something.
  541. else:
  542. formset = AuthorFormSet()
  543. return render_to_response("manage_authors.html", {
  544. "formset": formset,
  545. })
  546. As you can see, the view logic of a model formset isn't drastically different
  547. than that of a "normal" formset. The only difference is that we call
  548. ``formset.save()`` to save the data into the database. (This was described
  549. above, in :ref:`saving-objects-in-the-formset`.)
  550. Overiding ``clean()`` on a ``model_formset``
  551. --------------------------------------------
  552. Just like with ``ModelForms``, by default the ``clean()`` method of a
  553. ``model_formset`` will validate that none of the items in the formset violate
  554. the unique constraints on your model (either ``unique``, ``unique_together`` or
  555. ``unique_for_date|month|year``). If you want to override the ``clean()`` method
  556. on a ``model_formset`` and maintain this validation, you must call the parent
  557. class's ``clean`` method::
  558. class MyModelFormSet(BaseModelFormSet):
  559. def clean(self):
  560. super(MyModelFormSet, self).clean()
  561. # example custom validation across forms in the formset:
  562. for form in self.forms:
  563. # your custom formset validation
  564. Using a custom queryset
  565. -----------------------
  566. As stated earlier, you can override the default queryset used by the model
  567. formset::
  568. def manage_authors(request):
  569. AuthorFormSet = modelformset_factory(Author)
  570. if request.method == "POST":
  571. formset = AuthorFormSet(request.POST, request.FILES,
  572. queryset=Author.objects.filter(name__startswith='O'))
  573. if formset.is_valid():
  574. formset.save()
  575. # Do something.
  576. else:
  577. formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O'))
  578. return render_to_response("manage_authors.html", {
  579. "formset": formset,
  580. })
  581. Note that we pass the ``queryset`` argument in both the ``POST`` and ``GET``
  582. cases in this example.
  583. Using the formset in the template
  584. ---------------------------------
  585. .. highlight:: html+django
  586. There are three ways to render a formset in a Django template.
  587. First, you can let the formset do most of the work::
  588. <form method="post" action="">
  589. {{ formset }}
  590. </form>
  591. Second, you can manually render the formset, but let the form deal with
  592. itself::
  593. <form method="post" action="">
  594. {{ formset.management_form }}
  595. {% for form in formset %}
  596. {{ form }}
  597. {% endfor %}
  598. </form>
  599. When you manually render the forms yourself, be sure to render the management
  600. form as shown above. See the :ref:`management form documentation
  601. <understanding-the-managementform>`.
  602. Third, you can manually render each field::
  603. <form method="post" action="">
  604. {{ formset.management_form }}
  605. {% for form in formset %}
  606. {% for field in form %}
  607. {{ field.label_tag }}: {{ field }}
  608. {% endfor %}
  609. {% endfor %}
  610. </form>
  611. If you opt to use this third method and you don't iterate over the fields with
  612. a ``{% for %}`` loop, you'll need to render the primary key field. For example,
  613. if you were rendering the ``name`` and ``age`` fields of a model::
  614. <form method="post" action="">
  615. {{ formset.management_form }}
  616. {% for form in formset %}
  617. {{ form.id }}
  618. <ul>
  619. <li>{{ form.name }}</li>
  620. <li>{{ form.age }}</li>
  621. </ul>
  622. {% endfor %}
  623. </form>
  624. Notice how we need to explicitly render ``{{ form.id }}``. This ensures that
  625. the model formset, in the ``POST`` case, will work correctly. (This example
  626. assumes a primary key named ``id``. If you've explicitly defined your own
  627. primary key that isn't called ``id``, make sure it gets rendered.)
  628. .. highlight:: python
  629. .. _inline-formsets:
  630. Inline formsets
  631. ===============
  632. Inline formsets is a small abstraction layer on top of model formsets. These
  633. simplify the case of working with related objects via a foreign key. Suppose
  634. you have these two models::
  635. class Author(models.Model):
  636. name = models.CharField(max_length=100)
  637. class Book(models.Model):
  638. author = models.ForeignKey(Author)
  639. title = models.CharField(max_length=100)
  640. If you want to create a formset that allows you to edit books belonging to
  641. a particular author, you could do this::
  642. >>> from django.forms.models import inlineformset_factory
  643. >>> BookFormSet = inlineformset_factory(Author, Book)
  644. >>> author = Author.objects.get(name=u'Mike Royko')
  645. >>> formset = BookFormSet(instance=author)
  646. .. note::
  647. :func:`~django.forms.models.inlineformset_factory` uses
  648. :func:`~django.forms.models.modelformset_factory` and marks
  649. ``can_delete=True``.
  650. .. seealso::
  651. :ref:`Manually rendered can_delete and can_order <manually-rendered-can-delete-and-can-order>`.
  652. More than one foreign key to the same model
  653. -------------------------------------------
  654. If your model contains more than one foreign key to the same model, you'll
  655. need to resolve the ambiguity manually using ``fk_name``. For example, consider
  656. the following model::
  657. class Friendship(models.Model):
  658. from_friend = models.ForeignKey(Friend)
  659. to_friend = models.ForeignKey(Friend)
  660. length_in_months = models.IntegerField()
  661. To resolve this, you can use ``fk_name`` to
  662. :func:`~django.forms.models.inlineformset_factory`::
  663. >>> FriendshipFormSet = inlineformset_factory(Friend, Friendship, fk_name="from_friend")
  664. Using an inline formset in a view
  665. ---------------------------------
  666. You may want to provide a view that allows a user to edit the related objects
  667. of a model. Here's how you can do that::
  668. def manage_books(request, author_id):
  669. author = Author.objects.get(pk=author_id)
  670. BookInlineFormSet = inlineformset_factory(Author, Book)
  671. if request.method == "POST":
  672. formset = BookInlineFormSet(request.POST, request.FILES, instance=author)
  673. if formset.is_valid():
  674. formset.save()
  675. # Do something. Should generally end with a redirect. For example:
  676. return HttpResponseRedirect(author.get_absolute_url())
  677. else:
  678. formset = BookInlineFormSet(instance=author)
  679. return render_to_response("manage_books.html", {
  680. "formset": formset,
  681. })
  682. Notice how we pass ``instance`` in both the ``POST`` and ``GET`` cases.