django/docs/ref/forms/models.txt
2025-10-20 16:34:53 +00:00

359 lines
12 KiB
Text

===========
Model forms
===========
.. module:: django.forms.models
:synopsis: ModelForm API reference for inner ``Meta`` class and factory
functions
.. currentmodule:: django.forms
``ModelForm`` API reference. For introductory material about using a
``ModelForm``, see the :doc:`/topics/forms/modelforms` topic guide.
Model form ``Meta`` API
=======================
.. class:: ModelFormOptions
The ``_meta`` API is used to build forms that reflect a Django model. It is
accessible through the ``_meta`` attribute of each model form, and is an
``django.forms.models.ModelFormOptions`` instance.
The structure of the generated form can be customized by defining metadata
options as attributes of an inner ``Meta`` class. For example::
from django.forms import ModelForm
from myapp.models import Book
class BookForm(ModelForm):
class Meta:
model = Book
fields = ["title", "author"]
help_texts = {
"title": "The title of the book",
"author": "The author of the book",
}
# ... other attributes
Required attributes are :attr:`~ModelFormOptions.model`, and either
:attr:`~ModelFormOptions.fields` or :attr:`~ModelFormOptions.exclude`. All
other ``Meta`` attributes are optional.
Optional attributes, other than :attr:`~ModelFormOptions.localized_fields` and
:attr:`~ModelFormOptions.formfield_callback`, expect a dictionary that maps a
model field name to a value. Any field that is not defined in the dictionary
falls back to the field's default value.
.. admonition:: Invalid field names
Invalid or excluded field names in an optional dictionary attribute have no
effect, since fields that are not included are not accessed.
.. admonition:: Invalid Meta class attributes
You may define any attribute on a ``Meta`` class. Typos or incorrect
attribute names do not raise an error.
``error_messages``
------------------
.. attribute:: ModelFormOptions.error_messages
A dictionary that maps a model field name to a dictionary of error message
keys (``null``, ``blank``, ``invalid``, ``unique``, etc.) mapped to custom
error messages.
When a field is not specified, Django will fall back on the error messages
defined in that model field's :attr:`django.db.models.Field.error_messages`
and then finally on the default error messages for that field type.
``exclude``
-----------
.. attribute:: ModelFormOptions.exclude
A tuple or list of :attr:`~ModelFormOptions.model` field names to be
excluded from the form.
Either :attr:`~ModelFormOptions.fields` or
:attr:`~ModelFormOptions.exclude` must be set. If neither are set, an
:class:`~django.core.exceptions.ImproperlyConfigured` exception will be
raised. If :attr:`~ModelFormOptions.exclude` is set and
:attr:`~ModelFormOptions.fields` is unset, all model fields, except for
those specified in :attr:`~ModelFormOptions.exclude`, are included in the
form.
``field_classes``
-----------------
.. attribute:: ModelFormOptions.field_classes
A dictionary that maps a model field name to a :class:`~django.forms.Field`
class, which overrides the ``form_class`` used in the model field's
:meth:`.Field.formfield` method.
When a field is not specified, Django will fall back on the model field's
:ref:`default field class <model-form-field-types>`.
``fields``
----------
.. attribute:: ModelFormOptions.fields
A tuple or list of :attr:`~ModelFormOptions.model` field names to be
included in the form. The value ``'__all__'`` can be used to specify that
all fields should be included.
If any field is specified in :attr:`~ModelFormOptions.exclude`, this will
not be included in the form despite being specified in
:attr:`~ModelFormOptions.fields`.
Either :attr:`~ModelFormOptions.fields` or
:attr:`~ModelFormOptions.exclude` must be set. If neither are set, an
:class:`~django.core.exceptions.ImproperlyConfigured` exception will be
raised.
``formfield_callback``
----------------------
.. attribute:: ModelFormOptions.formfield_callback
A function or callable that takes a model field and returns a
:class:`django.forms.Field` object.
``help_texts``
--------------
.. attribute:: ModelFormOptions.help_texts
A dictionary that maps a model field name to a help text string.
When a field is not specified, Django will fall back on that model field's
:attr:`~django.db.models.Field.help_text`.
``labels``
----------
.. attribute:: ModelFormOptions.labels
A dictionary that maps a model field names to a label string.
When a field is not specified, Django will fall back on that model field's
:attr:`~django.db.models.Field.verbose_name` and then the field's attribute
name.
``localized_fields``
--------------------
.. attribute:: ModelFormOptions.localized_fields
A tuple or list of :attr:`~ModelFormOptions.model` field names to be
localized. The value ``'__all__'`` can be used to specify that all fields
should be localized.
By default, form fields are not localized, see
:ref:`enabling localization of fields
<modelforms-enabling-localization-of-fields>` for more details.
``model``
---------
.. attribute:: ModelFormOptions.model
Required. The :class:`django.db.models.Model` to be used for the
:class:`~django.forms.ModelForm`.
``widgets``
-----------
.. attribute:: ModelFormOptions.widgets
A dictionary that maps a model field name to a
:class:`django.forms.Widget`.
When a field is not specified, Django will fall back on the default widget
for that particular type of :class:`django.db.models.Field`.
Model form factory functions
============================
.. currentmodule:: django.forms.models
Creating Model Forms
====================
``modelform_factory``
---------------------
.. function:: modelform_factory(model, form=ModelForm, fields=None, exclude=None, formfield_callback=None, widgets=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, field_classes=None)
Returns a :class:`~django.forms.ModelForm` class for the given ``model``.
You can optionally pass a ``form`` argument to use as a starting point for
constructing the ``ModelForm``.
``fields`` is an optional list of field names. If provided, only the named
fields will be included in the returned fields.
``exclude`` is an optional list of field names. If provided, the named
fields will be excluded from the returned fields, even if they are listed
in the ``fields`` argument.
``formfield_callback`` is a callable that takes a model field and returns
a form field.
``widgets`` is a dictionary of model field names mapped to a widget.
``localized_fields`` is a list of names of fields which should be
localized.
``labels`` is a dictionary of model field names mapped to a label.
``help_texts`` is a dictionary of model field names mapped to a help text.
``error_messages`` is a dictionary of model field names mapped to a
dictionary of error messages.
``field_classes`` is a dictionary of model field names mapped to a form
field class.
See :ref:`modelforms-factory` for example usage.
You must provide the list of fields explicitly, either via keyword
arguments ``fields`` or ``exclude``, or the corresponding attributes on the
form's inner ``Meta`` class. See :ref:`modelforms-selecting-fields` for
more information. Omitting any definition of the fields to use will result
in an :exc:`~django.core.exceptions.ImproperlyConfigured` exception.
Creating Model Formsets
=======================
There are two ways to create model formsets in Django:
``modelformset_factory``
------------------------
.. function:: modelformset_factory(model, form=ModelForm, formfield_callback=None, formset=BaseModelFormSet, extra=1, can_delete=False, can_order=False, max_num=None, fields=None, exclude=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None, absolute_max=None, can_delete_extra=True, renderer=None, edit_only=False)
Returns a ``FormSet`` class for the given ``model`` class.
Arguments ``model``, ``form``, ``fields``, ``exclude``,
``formfield_callback``, ``widgets``, ``localized_fields``, ``labels``,
``help_texts``, ``error_messages``, and ``field_classes`` are all passed
through to :func:`~django.forms.models.modelform_factory`.
Arguments ``formset``, ``extra``, ``can_delete``, ``can_order``,
``max_num``, ``validate_max``, ``min_num``, ``validate_min``,
``absolute_max``, ``can_delete_extra``, and ``renderer`` are passed
through to :func:`~django.forms.formsets.formset_factory`. See
:doc:`formsets </topics/forms/formsets>` for details.
The ``edit_only`` argument allows :ref:`preventing new objects creation
<model-formsets-edit-only>`.
See :ref:`model-formsets` for example usage.
Declarative ``ModelFormSet``
----------------------------
.. class:: ModelFormSet
A BaseModelFormSet subclass that allows declarative declaration of
model formsets.
.. versionadded:: 5.1
Returns a ``ModelFormSet`` class for the given ``model`` class.
The same arguments that can be passed to the
``modelformset_factory`` function can also be passed to the
declarative syntax.
See the following example which shows how to create AuthorFormSet from
``Author`` model::
.. code-block:: pycon
>>> from django.forms import models
>>> from myapp.models import Author
>>> class AuthorFormSet(models.ModelFormSet):
... model = Author
... fields = ["field1", "field2"]
... exclude = ["field3"]
... extra = 2
... can_order = True
... can_delete = True
... max_num = 10
... validate_max = True
... min_num = 3
... validate_min = True
... absolute_max = 15
... can_delete_extra = False
... widgets = {"field1": TextInput(), "field2": Textarea()}
...
The same arguments that can be passed to the ``modelformset_factory``
function can also be passed to the declarative syntax.
You can also create your model formset without explicitly specifying the
model and fields, as they can be inferred from the form class. As shown
in the example below:
.. code-block:: pycon
>>> from django.forms import models
>>> from myapp.forms import PostForm
>>> class PostFormSet(models.ModelFormSet):
... form = PostForm # Specify the form class
... extra = 2
...
Creating Inline Formsets
========================
There are two ways to create inline formsets in Django:
``inlineformset_factory``
-------------------------
.. function:: inlineformset_factory(parent_model, model, form=ModelForm, formset=BaseInlineFormSet, fk_name=None, fields=None, exclude=None, extra=3, can_order=False, can_delete=True, max_num=None, formfield_callback=None, widgets=None, validate_max=False, localized_fields=None, labels=None, help_texts=None, error_messages=None, min_num=None, validate_min=False, field_classes=None, absolute_max=None, can_delete_extra=True, renderer=None, edit_only=False)
Returns an ``InlineFormSet`` using :func:`modelformset_factory` with
defaults of ``formset=``:class:`~django.forms.models.BaseInlineFormSet`,
``can_delete=True``, and ``extra=3``.
If your model has more than one :class:`~django.db.models.ForeignKey` to
the ``parent_model``, you must specify a ``fk_name``.
See :ref:`inline-formsets` for example usage.
Declarative ``InlineFormSet``
-----------------------------
.. class:: InlineFormSet
A BaseInlineFormSet subclass that allows declarative declaration of
model formsets.
.. versionadded:: 5.1
Returns a ``InlineFormSet`` class for the given ``parent_model`` and
``model`` class.
The Declarative ``InlineFormSet`` class takes the same arguments as
the :func:`inlineformset_factory` function.
.. code-block:: pycon
>>> from django.forms import models
>>> from myapp.models import Author, Book
>>> class BookFormSet(models.InlineFormSet):
... parent_model = Author
... model = Book
... extra = 1
... fields = "__all__"
...