Django: changing the DOM identifier at the form field level

I understand that by default, Django automatically populates the id for each form field when rendering with the format id_for_%s . You can change the format by providing the auto_id argument auto_id different format as its value to the form constructor.

This is not exactly what I am looking for. What I want to accomplish is to change the identifier of only one of the many fields in my form. In addition, the solution should not violate the use of form = MyForm(request.POST) .

PS. MyForm is a model form, so each identifier is derived from the corresponding field of the model.

Thanks for the help.

+8
django django-forms
source share
1 answer

The form structure seems to generate labels here:

 def _id_for_label(self): """ Wrapper around the field widget `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) 

This means that you can simply specify the field widget with the id key to set it as you wish.

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

Or override init and set attrs after the form is initialized.

I don’t see how this can disrupt the form, since the django forms structure never knows about HTML identifiers (this data is not transmitted to the server ...)

+15
source share

All Articles