How to get form fields' id in Django

DjangoDjango FormsDjango Templates

Django Problem Overview


Is there any way to get the id of a field in a template?

In the HTML I get: <input name="field_name" id="id_field_name"...

I know I can get the name with {{ field.html_name }}, but is there anything similar for getting the id?
Or can I only get it like this: id_{{ field.html_name }}?

Django Solutions


Solution 1 - Django

You can get the ID like this:

{{ field.auto_id }}

Solution 2 - Django

You can also use id_for_label:

{{ field.id_for_label }}

Solution 3 - Django

This doesn't work for every form field.

For instance {{ form.address.auto_id }} works while {{ form.address.auto_name }} will not.

However you can use {{ form.address.html_name }} to get the equivalent answer.

Here are the https://docs.djangoproject.com/en/dev/topics/forms/">docs</a>

Solution 4 - Django

In Django 2 you can retrieve the ID for a specific field using {{ field.id_for_label }}

This is documented here.

Solution 5 - Django

From the documentation-

> each form field has an ID attribute set to id_<field-name> > , which is referenced by the accompanying label tag. This is important in ensuring that forms are accessible to assistive technology such as screen reader software. You can also customize the way in which labels and ids are generated.

So I would like to say id_field-name , you collect the field name from the model.

Here is the link to the documentation

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser182945View Question on Stackoverflow
Solution 1 - DjangoWill HardyView Answer on Stackoverflow
Solution 2 - DjangoEren SüleymanoğluView Answer on Stackoverflow
Solution 3 - DjangokkaehlerView Answer on Stackoverflow
Solution 4 - DjangoLondonAppDevView Answer on Stackoverflow
Solution 5 - DjangoqazView Answer on Stackoverflow