Skip to content

Commit a56b232

Browse files
committed
[1.1.X] Fixed #13184 -- Document the requirement that custom model fields using SubfieldBase should probably implement formfield. Thanks to Mark L. for the report, and to Joseph and Honza for the guidance on the solution.
Backport of r12979 from trunk. git-svn-id: http://code.djangoproject.com/svn/django/branches/releases/1.1.X@12980 bcc190cf-cafb-0310-a4f2-bffc1f526a37
1 parent a33c767 commit a56b232

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

docs/howto/custom-model-fields.txt

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -261,6 +261,28 @@ For example::
261261
This ensures that the :meth:`to_python` method, documented below, will always be
262262
called when the attribute is initialized.
263263

264+
ModelForms and custom fields
265+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
266+
267+
If you use :class:`~django.db.models.SubfieldBase`, :meth:`to_python`
268+
will be called every time an instance of the field is assigned a
269+
value. This means that whenever a value may be assigned to the field,
270+
you need to ensure that it will be of the correct datatype, or that
271+
you handle any exceptions.
272+
273+
This is especially important if you use :ref:`ModelForms
274+
<topics-forms-modelforms>`. When saving a ModelForm, Django will use
275+
form values to instantiate model instances. However, if the cleaned
276+
form data can't be used as valid input to the field, the normal form
277+
validation process will break.
278+
279+
Therefore, you must ensure that the form field used to represent your
280+
custom field performs whatever input validation and data cleaning is
281+
necessary to convert user-provided form input into a
282+
`to_python()`-compatible model field value. This may require writing a
283+
custom form field, and/or implementing the :meth:`formfield` method on
284+
your field to return a form field class whose `to_python()` returns the
285+
correct datatype.
264286

265287
Documenting your Custom Field
266288
-----------------------------

0 commit comments

Comments
 (0)