Refs #31026 -- Improved BoundField.label_tag() docs.

This commit is contained in:
David Smith 2021-10-02 07:14:51 +01:00 committed by Mariusz Felisiak
parent 2116238d5f
commit 9be36f8044
1 changed files with 27 additions and 11 deletions

View File

@ -1210,6 +1210,29 @@ Methods of ``BoundField``
.. method:: BoundField.label_tag(contents=None, attrs=None, label_suffix=None) .. method:: BoundField.label_tag(contents=None, attrs=None, label_suffix=None)
Renders a label tag for the form field using the template specified by
:attr:`.Form.template_name_label`.
The available context is:
* ``field``: This instance of the :class:`BoundField`.
* ``contents``: By default a concatenated string of
:attr:`BoundField.label` and :attr:`Form.label_suffix` (or
:attr:`Field.label_suffix`, if set). This can be overridden by the
``contents`` and ``label_suffix`` arguments.
* ``attrs``: A ``dict`` containing ``for``,
:attr:`Form.required_css_class`, and ``id``. ``id`` is generated by the
field's widget ``attrs`` or :attr:`BoundField.auto_id`. Additional
attributes can be provided by the ``attrs`` argument.
* ``use_tag``: A boolean which is ``True`` if the label has an ``id``.
If ``False`` the default template omits the ``<label>`` tag.
.. tip::
In your template ``field`` is the instance of the ``BoundField``.
Therefore ``field.field`` accesses :attr:`BoundField.field` being
the field you declare, e.g. ``forms.CharField``.
To separately render the label tag of a form field, you can call its To separately render the label tag of a form field, you can call its
``label_tag()`` method:: ``label_tag()`` method::
@ -1217,17 +1240,10 @@ Methods of ``BoundField``
>>> print(f['message'].label_tag()) >>> print(f['message'].label_tag())
<label for="id_message">Message:</label> <label for="id_message">Message:</label>
You can provide the ``contents`` parameter which will replace the If you'd like to customize the rendering this can be achieved by overriding
auto-generated label tag. An ``attrs`` dictionary may contain additional the :attr:`.Form.template_name_label` attribute or more generally by
attributes for the ``<label>`` tag. overriding the default template, see also
:ref:`overriding-built-in-form-templates`.
The HTML that's generated includes the form's
:attr:`~django.forms.Form.label_suffix` (a colon, by default) or, if set,
the current field's :attr:`~django.forms.Field.label_suffix`. The optional
``label_suffix`` parameter allows you to override any previously set
suffix. For example, you can use an empty string to hide the label on
selected fields. The label is rendered using the template specified by the
forms :attr:`.Form.template_name_label`.
.. versionchanged:: 4.0 .. versionchanged:: 4.0