summaryrefslogtreecommitdiff
path: root/docs
diff options
context:
space:
mode:
authorClifford Gama <cliffygamy@gmail.com>2024-09-10 22:38:01 +0200
committerSarah Boyce <42296566+sarahboyce@users.noreply.github.com>2024-09-19 15:19:08 +0200
commite1d226bc1c52a0165164e5b34fef1d336050ca60 (patch)
treeda785fdf59a4bdaf12ab50840e261d4976da01bb /docs
parent4b65dc2f217d705ad9438212f38a31ac8c7d58ba (diff)
Fixed #35748 -- Documented that fields are excluded from a ModelForm when formfield() returns None.
Co-authored-by: Sarah Boyce <42296566+sarahboyce@users.noreply.github.com>
Diffstat (limited to 'docs')
-rw-r--r--docs/howto/custom-model-fields.txt11
-rw-r--r--docs/ref/models/fields.txt3
2 files changed, 12 insertions, 2 deletions
diff --git a/docs/howto/custom-model-fields.txt b/docs/howto/custom-model-fields.txt
index b4a1537896..fefd8740e7 100644
--- a/docs/howto/custom-model-fields.txt
+++ b/docs/howto/custom-model-fields.txt
@@ -645,6 +645,9 @@ delegate further handling to the parent class. This might require you to write
a custom form field (and even a form widget). See the :doc:`forms documentation
</topics/forms/index>` for information about this.
+If you wish to exclude the field from the :class:`~django.forms.ModelForm`, you
+can override the :meth:`~Field.formfield` method to return ``None``.
+
Continuing our ongoing example, we can write the :meth:`~Field.formfield` method
as::
@@ -652,8 +655,12 @@ as::
# ...
def formfield(self, **kwargs):
- # This is a fairly standard way to set up some defaults
- # while letting the caller override them.
+ # Exclude the field from the ModelForm when some condition is met.
+ some_condition = kwargs.get("some_condition", False)
+ if some_condition:
+ return None
+
+ # Set up some defaults while letting the caller override them.
defaults = {"form_class": MyFormField}
defaults.update(kwargs)
return super().formfield(**defaults)
diff --git a/docs/ref/models/fields.txt b/docs/ref/models/fields.txt
index 5266135dd2..899947c17f 100644
--- a/docs/ref/models/fields.txt
+++ b/docs/ref/models/fields.txt
@@ -2445,6 +2445,9 @@ Field API reference
Returns the default :class:`django.forms.Field` of this field for
:class:`~django.forms.ModelForm`.
+ If :meth:`~Field.formfield` is overridden to return ``None``, this field
+ is excluded from the :class:`~django.forms.ModelForm`.
+
By default, if both ``form_class`` and ``choices_form_class`` are
``None``, it uses :class:`~django.forms.CharField`. If the field has
:attr:`~django.db.models.Field.choices` and ``choices_form_class``