modelforms.txt 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874
  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. ``ManyToManyField`` ``ModelMultipleChoiceField`` (see
  58. below)
  59. ``NullBooleanField`` ``CharField``
  60. ``PhoneNumberField`` ``USPhoneNumberField``
  61. (from ``django.contrib.localflavor.us``)
  62. ``PositiveIntegerField`` ``IntegerField``
  63. ``PositiveSmallIntegerField`` ``IntegerField``
  64. ``SlugField`` ``SlugField``
  65. ``SmallIntegerField`` ``IntegerField``
  66. ``TextField`` ``CharField`` with
  67. ``widget=forms.Textarea``
  68. ``TimeField`` ``TimeField``
  69. ``URLField`` ``URLField`` with ``verify_exists`` set
  70. to the model field's ``verify_exists``
  71. ``XMLField`` ``CharField`` with
  72. ``widget=forms.Textarea``
  73. =============================== ========================================
  74. .. versionadded:: 1.2
  75. The ``BigIntegerField`` is new in Django 1.2.
  76. As you might expect, the ``ForeignKey`` and ``ManyToManyField`` model field
  77. types are special cases:
  78. * ``ForeignKey`` is represented by ``django.forms.ModelChoiceField``,
  79. which is a ``ChoiceField`` whose choices are a model ``QuerySet``.
  80. * ``ManyToManyField`` is represented by
  81. ``django.forms.ModelMultipleChoiceField``, which is a
  82. ``MultipleChoiceField`` whose choices are a model ``QuerySet``.
  83. In addition, each generated form field has attributes set as follows:
  84. * If the model field has ``blank=True``, then ``required`` is set to
  85. ``False`` on the form field. Otherwise, ``required=True``.
  86. * The form field's ``label`` is set to the ``verbose_name`` of the model
  87. field, with the first character capitalized.
  88. * The form field's ``help_text`` is set to the ``help_text`` of the model
  89. field.
  90. * If the model field has ``choices`` set, then the form field's ``widget``
  91. will be set to ``Select``, with choices coming from the model field's
  92. ``choices``. The choices will normally include the blank choice which is
  93. selected by default. If the field is required, this forces the user to
  94. make a selection. The blank choice will not be included if the model
  95. field has ``blank=False`` and an explicit ``default`` value (the
  96. ``default`` value will be initially selected instead).
  97. Finally, note that you can override the form field used for a given model
  98. field. See `Overriding the default field types or widgets`_ below.
  99. A full example
  100. --------------
  101. Consider this set of models::
  102. from django.db import models
  103. from django.forms import ModelForm
  104. TITLE_CHOICES = (
  105. ('MR', 'Mr.'),
  106. ('MRS', 'Mrs.'),
  107. ('MS', 'Ms.'),
  108. )
  109. class Author(models.Model):
  110. name = models.CharField(max_length=100)
  111. title = models.CharField(max_length=3, choices=TITLE_CHOICES)
  112. birth_date = models.DateField(blank=True, null=True)
  113. def __unicode__(self):
  114. return self.name
  115. class Book(models.Model):
  116. name = models.CharField(max_length=100)
  117. authors = models.ManyToManyField(Author)
  118. class AuthorForm(ModelForm):
  119. class Meta:
  120. model = Author
  121. class BookForm(ModelForm):
  122. class Meta:
  123. model = Book
  124. With these models, the ``ModelForm`` subclasses above would be roughly
  125. equivalent to this (the only difference being the ``save()`` method, which
  126. we'll discuss in a moment.)::
  127. class AuthorForm(forms.Form):
  128. name = forms.CharField(max_length=100)
  129. title = forms.CharField(max_length=3,
  130. widget=forms.Select(choices=TITLE_CHOICES))
  131. birth_date = forms.DateField(required=False)
  132. class BookForm(forms.Form):
  133. name = forms.CharField(max_length=100)
  134. authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all())
  135. The ``is_valid()`` method and ``errors``
  136. ----------------------------------------
  137. .. versionchanged:: 1.2
  138. The first time you call ``is_valid()`` or access the ``errors`` attribute of a
  139. ``ModelForm`` has always triggered form validation, but as of Django 1.2, it
  140. will also trigger :ref:`model validation <validating-objects>`. This has the
  141. side-effect of cleaning the model you pass to the ``ModelForm`` constructor.
  142. For instance, calling ``is_valid()`` on your form will convert any date fields
  143. on your model to actual date objects.
  144. The ``save()`` method
  145. ---------------------
  146. Every form produced by ``ModelForm`` also has a ``save()``
  147. method. This method creates and saves a database object from the data
  148. bound to the form. A subclass of ``ModelForm`` can accept an existing
  149. model instance as the keyword argument ``instance``; if this is
  150. supplied, ``save()`` will update that instance. If it's not supplied,
  151. ``save()`` will create a new instance of the specified model::
  152. # Create a form instance from POST data.
  153. >>> f = ArticleForm(request.POST)
  154. # Save a new Article object from the form's data.
  155. >>> new_article = f.save()
  156. # Create a form to edit an existing Article.
  157. >>> a = Article.objects.get(pk=1)
  158. >>> f = ArticleForm(instance=a)
  159. >>> f.save()
  160. # Create a form to edit an existing Article, but use
  161. # POST data to populate the form.
  162. >>> a = Article.objects.get(pk=1)
  163. >>> f = ArticleForm(request.POST, instance=a)
  164. >>> f.save()
  165. Note that ``save()`` will raise a ``ValueError`` 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 ``title`` fields, you would
  227. specify ``fields`` or ``exclude`` like this::
  228. class PartialAuthorForm(ModelForm):
  229. class Meta:
  230. model = Author
  231. fields = ('name', 'title')
  232. class PartialAuthorForm(ModelForm):
  233. class Meta:
  234. model = Author
  235. exclude = ('birth_date',)
  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 will not
  241. be set by the form's ``save()`` method. Django will prevent any attempt to
  242. save an incomplete model, so if the model does not allow the missing fields
  243. to be empty, and does not provide a default value for the missing fields,
  244. any attempt to ``save()`` a ``ModelForm`` with missing fields will fail.
  245. To avoid this failure, you must instantiate your model with initial values
  246. for the missing, but required fields::
  247. author = Author(title='Mr')
  248. form = PartialAuthorForm(request.POST, instance=author)
  249. form.save()
  250. Alternatively, you can use ``save(commit=False)`` and manually set
  251. any extra required fields::
  252. form = PartialAuthorForm(request.POST)
  253. author = form.save(commit=False)
  254. author.title = 'Mr'
  255. author.save()
  256. See the `section on saving forms`_ for more details on using
  257. ``save(commit=False)``.
  258. .. _section on saving forms: `The save() method`_
  259. Overriding the default field types or widgets
  260. ---------------------------------------------
  261. .. versionadded:: 1.2
  262. The ``widgets`` attribute is new in Django 1.2.
  263. The default field types, as described in the `Field types`_ table above, are
  264. sensible defaults. If you have a ``DateField`` in your model, chances are you'd
  265. want that to be represented as a ``DateField`` in your form. But
  266. ``ModelForm`` gives you the flexibility of changing the form field type and
  267. widget for a given model field.
  268. To specify a custom widget for a field, use the ``widgets`` attribute of the
  269. inner ``Meta`` class. This should be a dictionary mapping field names to widget
  270. classes or instances.
  271. For example, if you want the a ``CharField`` for the ``name``
  272. attribute of ``Author`` to be represented by a ``<textarea>`` instead
  273. of its default ``<input type="text">``, you can override the field's
  274. widget::
  275. from django.forms import ModelForm, Textarea
  276. class AuthorForm(ModelForm):
  277. class Meta:
  278. model = Author
  279. fields = ('name', 'title', 'birth_date')
  280. widgets = {
  281. 'name': Textarea(attrs={'cols': 80, 'rows': 20}),
  282. }
  283. The ``widgets`` dictionary accepts either widget instances (e.g.,
  284. ``Textarea(...)``) or classes (e.g., ``Textarea``).
  285. If you want to further customize a field -- including its type, label, etc. --
  286. you can do this by declaratively specifying fields like you would in a regular
  287. ``Form``. Declared fields will override the default ones generated by using the
  288. ``model`` attribute.
  289. For example, if you wanted to use ``MyDateFormField`` for the ``pub_date``
  290. field, you could do the following::
  291. class ArticleForm(ModelForm):
  292. pub_date = MyDateFormField()
  293. class Meta:
  294. model = Article
  295. If you want to override a field's default label, then specify the ``label``
  296. parameter when declaring the form field::
  297. >>> class ArticleForm(ModelForm):
  298. ... pub_date = DateField(label='Publication date')
  299. ...
  300. ... class Meta:
  301. ... model = Article
  302. .. note::
  303. If you explicitly instantiate a form field like this, Django assumes that you
  304. want to completely define its behavior; therefore, default attributes (such as
  305. ``max_length`` or ``required``) are not drawn from the corresponding model. If
  306. you want to maintain the behavior specified in the model, you must set the
  307. relevant arguments explicitly when declaring the form field.
  308. For example, if the ``Article`` model looks like this::
  309. class Article(models.Model):
  310. headline = models.CharField(max_length=200, null=True, blank=True,
  311. help_text="Use puns liberally")
  312. content = models.TextField()
  313. and you want to do some custom validation for ``headline``, while keeping
  314. the ``blank`` and ``help_text`` values as specified, you might define
  315. ``ArticleForm`` like this::
  316. class ArticleForm(ModelForm):
  317. headline = MyFormField(max_length=200, required=False,
  318. help_text="Use puns liberally")
  319. class Meta:
  320. model = Article
  321. See the :doc:`form field documentation </ref/forms/fields>` for more information
  322. on fields and their arguments.
  323. Changing the order of fields
  324. ----------------------------
  325. By default, a ``ModelForm`` will render fields in the same order that they are
  326. defined on the model, with ``ManyToManyField`` instances appearing last. If
  327. you want to change the order in which fields are rendered, you can use the
  328. ``fields`` attribute on the ``Meta`` class.
  329. The ``fields`` attribute defines the subset of model fields that will be
  330. rendered, and the order in which they will be rendered. For example given this
  331. model::
  332. class Book(models.Model):
  333. author = models.ForeignKey(Author)
  334. title = models.CharField(max_length=100)
  335. the ``author`` field would be rendered first. If we wanted the title field
  336. to be rendered first, we could specify the following ``ModelForm``::
  337. >>> class BookForm(ModelForm):
  338. ... class Meta:
  339. ... model = Book
  340. ... fields = ('title', 'author')
  341. .. _overriding-modelform-clean-method:
  342. Overriding the clean() method
  343. -----------------------------
  344. You can override the ``clean()`` method on a model form to provide additional
  345. validation in the same way you can on a normal form.
  346. In this regard, model forms have two specific characteristics when compared to
  347. forms:
  348. By default the ``clean()`` method validates the uniqueness of fields that are
  349. marked as ``unique``, ``unique_together`` or ``unique_for_date|month|year`` on
  350. the model. Therefore, if you would like to override the ``clean()`` method and
  351. maintain the default validation, you must call the parent class's ``clean()``
  352. method.
  353. Also, a model form instance bound to a model object will contain a
  354. ``self.instance`` attribute that gives model form methods access to that
  355. specific model instance.
  356. Form inheritance
  357. ----------------
  358. As with basic forms, you can extend and reuse ``ModelForms`` by inheriting
  359. them. This is useful if you need to declare extra fields or extra methods on a
  360. parent class for use in a number of forms derived from models. For example,
  361. using the previous ``ArticleForm`` class::
  362. >>> class EnhancedArticleForm(ArticleForm):
  363. ... def clean_pub_date(self):
  364. ... ...
  365. This creates a form that behaves identically to ``ArticleForm``, except there's
  366. some extra validation and cleaning for the ``pub_date`` field.
  367. You can also subclass the parent's ``Meta`` inner class if you want to change
  368. the ``Meta.fields`` or ``Meta.excludes`` lists::
  369. >>> class RestrictedArticleForm(EnhancedArticleForm):
  370. ... class Meta(ArticleForm.Meta):
  371. ... exclude = ('body',)
  372. This adds the extra method from the ``EnhancedArticleForm`` and modifies
  373. the original ``ArticleForm.Meta`` to remove one field.
  374. There are a couple of things to note, however.
  375. * Normal Python name resolution rules apply. If you have multiple base
  376. classes that declare a ``Meta`` inner class, only the first one will be
  377. used. This means the child's ``Meta``, if it exists, otherwise the
  378. ``Meta`` of the first parent, etc.
  379. * For technical reasons, a subclass cannot inherit from both a ``ModelForm``
  380. and a ``Form`` simultaneously.
  381. Chances are these notes won't affect you unless you're trying to do something
  382. tricky with subclassing.
  383. Interaction with model validation
  384. ---------------------------------
  385. As part of its validation process, ``ModelForm`` will call the ``clean()``
  386. method of each field on your model that has a corresponding field on your form.
  387. If you have excluded any model fields, validation will not be run on those
  388. fields. See the :doc:`form validation </ref/forms/validation>` documentation
  389. for more on how field cleaning and validation work. Also, your model's
  390. ``clean()`` method will be called before any uniqueness checks are made. See
  391. :ref:`Validating objects <validating-objects>` for more information on the
  392. model's ``clean()`` hook.
  393. .. _model-formsets:
  394. Model formsets
  395. ==============
  396. Like :doc:`regular formsets </topics/forms/formsets>`, Django provides a couple
  397. of enhanced formset classes that make it easy to work with Django models. Let's
  398. reuse the ``Author`` model from above::
  399. >>> from django.forms.models import modelformset_factory
  400. >>> AuthorFormSet = modelformset_factory(Author)
  401. This will create a formset that is capable of working with the data associated
  402. with the ``Author`` model. It works just like a regular formset::
  403. >>> formset = AuthorFormSet()
  404. >>> print formset
  405. <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" />
  406. <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>
  407. <tr><th><label for="id_form-0-title">Title:</label></th><td><select name="form-0-title" id="id_form-0-title">
  408. <option value="" selected="selected">---------</option>
  409. <option value="MR">Mr.</option>
  410. <option value="MRS">Mrs.</option>
  411. <option value="MS">Ms.</option>
  412. </select></td></tr>
  413. <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>
  414. .. note::
  415. ``modelformset_factory`` uses ``formset_factory`` to generate formsets.
  416. This means that a model formset is just an extension of a basic formset
  417. that knows how to interact with a particular model.
  418. Changing the queryset
  419. ---------------------
  420. By default, when you create a formset from a model, the formset will use a
  421. queryset that includes all objects in the model (e.g.,
  422. ``Author.objects.all()``). You can override this behavior by using the
  423. ``queryset`` argument::
  424. >>> formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O'))
  425. Alternatively, you can create a subclass that sets ``self.queryset`` in
  426. ``__init__``::
  427. from django.forms.models import BaseModelFormSet
  428. class BaseAuthorFormSet(BaseModelFormSet):
  429. def __init__(self, *args, **kwargs):
  430. super(BaseAuthorFormSet, self).__init__(*args, **kwargs)
  431. self.queryset = Author.objects.filter(name__startswith='O')
  432. Then, pass your ``BaseAuthorFormSet`` class to the factory function::
  433. >>> AuthorFormSet = modelformset_factory(Author, formset=BaseAuthorFormSet)
  434. If you want to return a formset that doesn't include *any* pre-existing
  435. instances of the model, you can specify an empty QuerySet::
  436. >>> AuthorFormSet(queryset=Author.objects.none())
  437. Controlling which fields are used with ``fields`` and ``exclude``
  438. -----------------------------------------------------------------
  439. By default, a model formset uses all fields in the model that are not marked
  440. with ``editable=False``. However, this can be overridden at the formset level::
  441. >>> AuthorFormSet = modelformset_factory(Author, fields=('name', 'title'))
  442. Using ``fields`` restricts the formset to use only the given fields.
  443. Alternatively, you can take an "opt-out" approach, specifying which fields to
  444. exclude::
  445. >>> AuthorFormSet = modelformset_factory(Author, exclude=('birth_date',))
  446. .. _saving-objects-in-the-formset:
  447. Saving objects in the formset
  448. -----------------------------
  449. As with a ``ModelForm``, you can save the data as a model object. This is done
  450. with the formset's ``save()`` method::
  451. # Create a formset instance with POST data.
  452. >>> formset = AuthorFormSet(request.POST)
  453. # Assuming all is valid, save the data.
  454. >>> instances = formset.save()
  455. The ``save()`` method returns the instances that have been saved to the
  456. database. If a given instance's data didn't change in the bound data, the
  457. instance won't be saved to the database and won't be included in the return
  458. value (``instances``, in the above example).
  459. Pass ``commit=False`` to return the unsaved model instances::
  460. # don't save to the database
  461. >>> instances = formset.save(commit=False)
  462. >>> for instance in instances:
  463. ... # do something with instance
  464. ... instance.save()
  465. This gives you the ability to attach data to the instances before saving them
  466. to the database. If your formset contains a ``ManyToManyField``, you'll also
  467. need to call ``formset.save_m2m()`` to ensure the many-to-many relationships
  468. are saved properly.
  469. .. _model-formsets-max-num:
  470. Limiting the number of editable objects
  471. ---------------------------------------
  472. .. versionchanged:: 1.2
  473. As with regular formsets, you can use the ``max_num`` and ``extra`` parameters
  474. to ``modelformset_factory`` to limit the number of extra forms displayed.
  475. ``max_num`` does not prevent existing objects from being displayed::
  476. >>> Author.objects.order_by('name')
  477. [<Author: Charles Baudelaire>, <Author: Paul Verlaine>, <Author: Walt Whitman>]
  478. >>> AuthorFormSet = modelformset_factory(Author, max_num=1)
  479. >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
  480. >>> [x.name for x in formset.get_queryset()]
  481. [u'Charles Baudelaire', u'Paul Verlaine', u'Walt Whitman']
  482. If the value of ``max_num`` is greater than the number of existing related
  483. objects, up to ``extra`` additional blank forms will be added to the formset,
  484. so long as the total number of forms does not exceed ``max_num``::
  485. >>> AuthorFormSet = modelformset_factory(Author, max_num=4, extra=2)
  486. >>> formset = AuthorFormSet(queryset=Author.objects.order_by('name'))
  487. >>> for form in formset:
  488. ... print form.as_table()
  489. <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>
  490. <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>
  491. <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>
  492. <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>
  493. .. versionchanged:: 1.2
  494. A ``max_num`` value of ``None`` (the default) puts no limit on the number of
  495. forms displayed.
  496. Using a model formset in a view
  497. -------------------------------
  498. Model formsets are very similar to formsets. Let's say we want to present a
  499. formset to edit ``Author`` model instances::
  500. def manage_authors(request):
  501. AuthorFormSet = modelformset_factory(Author)
  502. if request.method == 'POST':
  503. formset = AuthorFormSet(request.POST, request.FILES)
  504. if formset.is_valid():
  505. formset.save()
  506. # do something.
  507. else:
  508. formset = AuthorFormSet()
  509. return render_to_response("manage_authors.html", {
  510. "formset": formset,
  511. })
  512. As you can see, the view logic of a model formset isn't drastically different
  513. than that of a "normal" formset. The only difference is that we call
  514. ``formset.save()`` to save the data into the database. (This was described
  515. above, in :ref:`saving-objects-in-the-formset`.)
  516. Overiding ``clean()`` on a ``model_formset``
  517. --------------------------------------------
  518. Just like with ``ModelForms``, by default the ``clean()`` method of a
  519. ``model_formset`` will validate that none of the items in the formset violate
  520. the unique constraints on your model (either ``unique``, ``unique_together`` or
  521. ``unique_for_date|month|year``). If you want to overide the ``clean()`` method
  522. on a ``model_formset`` and maintain this validation, you must call the parent
  523. class's ``clean`` method::
  524. class MyModelFormSet(BaseModelFormSet):
  525. def clean(self):
  526. super(MyModelFormSet, self).clean()
  527. # example custom validation across forms in the formset:
  528. for form in self.forms:
  529. # your custom formset validation
  530. Using a custom queryset
  531. -----------------------
  532. As stated earlier, you can override the default queryset used by the model
  533. formset::
  534. def manage_authors(request):
  535. AuthorFormSet = modelformset_factory(Author)
  536. if request.method == "POST":
  537. formset = AuthorFormSet(request.POST, request.FILES,
  538. queryset=Author.objects.filter(name__startswith='O'))
  539. if formset.is_valid():
  540. formset.save()
  541. # Do something.
  542. else:
  543. formset = AuthorFormSet(queryset=Author.objects.filter(name__startswith='O'))
  544. return render_to_response("manage_authors.html", {
  545. "formset": formset,
  546. })
  547. Note that we pass the ``queryset`` argument in both the ``POST`` and ``GET``
  548. cases in this example.
  549. Using the formset in the template
  550. ---------------------------------
  551. .. highlight:: html+django
  552. There are three ways to render a formset in a Django template.
  553. First, you can let the formset do most of the work::
  554. <form method="post" action="">
  555. {{ formset }}
  556. </form>
  557. Second, you can manually render the formset, but let the form deal with
  558. itself::
  559. <form method="post" action="">
  560. {{ formset.management_form }}
  561. {% for form in formset %}
  562. {{ form }}
  563. {% endfor %}
  564. </form>
  565. When you manually render the forms yourself, be sure to render the management
  566. form as shown above. See the :ref:`management form documentation
  567. <understanding-the-managementform>`.
  568. Third, you can manually render each field::
  569. <form method="post" action="">
  570. {{ formset.management_form }}
  571. {% for form in formset %}
  572. {% for field in form %}
  573. {{ field.label_tag }}: {{ field }}
  574. {% endfor %}
  575. {% endfor %}
  576. </form>
  577. If you opt to use this third method and you don't iterate over the fields with
  578. a ``{% for %}`` loop, you'll need to render the primary key field. For example,
  579. if you were rendering the ``name`` and ``age`` fields of a model::
  580. <form method="post" action="">
  581. {{ formset.management_form }}
  582. {% for form in formset %}
  583. {{ form.id }}
  584. <ul>
  585. <li>{{ form.name }}</li>
  586. <li>{{ form.age }}</li>
  587. </ul>
  588. {% endfor %}
  589. </form>
  590. Notice how we need to explicitly render ``{{ form.id }}``. This ensures that
  591. the model formset, in the ``POST`` case, will work correctly. (This example
  592. assumes a primary key named ``id``. If you've explicitly defined your own
  593. primary key that isn't called ``id``, make sure it gets rendered.)
  594. .. highlight:: python
  595. Inline formsets
  596. ===============
  597. Inline formsets is a small abstraction layer on top of model formsets. These
  598. simplify the case of working with related objects via a foreign key. Suppose
  599. you have these two models::
  600. class Author(models.Model):
  601. name = models.CharField(max_length=100)
  602. class Book(models.Model):
  603. author = models.ForeignKey(Author)
  604. title = models.CharField(max_length=100)
  605. If you want to create a formset that allows you to edit books belonging to
  606. a particular author, you could do this::
  607. >>> from django.forms.models import inlineformset_factory
  608. >>> BookFormSet = inlineformset_factory(Author, Book)
  609. >>> author = Author.objects.get(name=u'Mike Royko')
  610. >>> formset = BookFormSet(instance=author)
  611. .. note::
  612. ``inlineformset_factory`` uses ``modelformset_factory`` and marks
  613. ``can_delete=True``.
  614. More than one foreign key to the same model
  615. -------------------------------------------
  616. If your model contains more than one foreign key to the same model, you'll
  617. need to resolve the ambiguity manually using ``fk_name``. For example, consider
  618. the following model::
  619. class Friendship(models.Model):
  620. from_friend = models.ForeignKey(Friend)
  621. to_friend = models.ForeignKey(Friend)
  622. length_in_months = models.IntegerField()
  623. To resolve this, you can use ``fk_name`` to ``inlineformset_factory``::
  624. >>> FriendshipFormSet = inlineformset_factory(Friend, Friendship, fk_name="from_friend")
  625. Using an inline formset in a view
  626. ---------------------------------
  627. You may want to provide a view that allows a user to edit the related objects
  628. of a model. Here's how you can do that::
  629. def manage_books(request, author_id):
  630. author = Author.objects.get(pk=author_id)
  631. BookInlineFormSet = inlineformset_factory(Author, Book)
  632. if request.method == "POST":
  633. formset = BookInlineFormSet(request.POST, request.FILES, instance=author)
  634. if formset.is_valid():
  635. formset.save()
  636. # Do something.
  637. else:
  638. formset = BookInlineFormSet(instance=author)
  639. return render_to_response("manage_books.html", {
  640. "formset": formset,
  641. })
  642. Notice how we pass ``instance`` in both the ``POST`` and ``GET`` cases.