[Solved]-Django: Change the DOM id at form field level

23đź‘Ť

âś…

The forms framework appears to generate labels here:

def _id_for_label(self):
    """
    Wrapper around the field widget's `id_for_label` class method.
    Useful, for example, for focusing on this field regardless of whether
    it has a single widget or a MutiWidget.
    """
    widget = self.field.widget
    id_ = widget.attrs.get('id') or self.auto_id
    return widget.id_for_label(id_)
id_for_label = property(_id_for_label)

Which means you can just supply your field widget with an “id” key to set it to whatever you’d like.

foo = forms.CharField(widget=forms.TextInput(attrs={'id': 'foobar'}))

Or override init and set the attrs after form initialization.

I don’t see how this could break a form as django’s forms framework isn’t ever aware of HTML ids (that data is not passed to the server…)

Leave a comment