When are a field's auto_id and id_for_label different?

I’m working more with forms at the moment and I’m constructing quite a lot from hand. I was wondering, when is form.field.auto_id ever not the same as form.myfield.id_for_label?

Isn’t this

<label for="{{ form.myfield.auto_id }}">{{ form.myfield.label }}</label>
<input id="{{ form.myfield.auto_id }}">

easier to read than this?

<label for="{{ form.myfield.id_for_label }}">{{ form.myfield.label }}</label>
<input id="{{ form.myfield.auto_id }}">

The docstring of id_for_label gives the explanation. See https://github.com/django/django/blob/main/django/forms/boundfield.py#L252

        Wrapper around the field widget's `id_for_label` method.
        Useful, for example, for focusing on this field regardless of whether
        it has a single widget or a MultiWidget.

Then

        Return the HTML ID attribute of this Widget for use by a <label>, given
        the ID of the field. Return an empty string if no ID is available.

        This hook is necessary because some widgets have multiple HTML
        elements and, thus, multiple IDs. In that case, this method should
        return an ID value that corresponds to the first ID in the widget's
        tags.
2 Likes