How to get Form Input ID, Label & Name in Django Template

In some cases, you'll want two have more control over the HTML forms in your Django templates and build inputs manually. In this tutorial, we will learn how to access the input ID, label and name of form properties that have been generated by Django.

 

Get Input ID

To get the ID for the input, access the auto_id property like this:

 

id="{{ form.input_name.auto_id }}"

 

Replace input_name with the variable name of your input as defined in forms.py.

 

Get Input Name

Here is how to get the input name:

 

name="{{ form.input_name.name }}"

 

Get Label

Here is how to get the label text:

 

{{ form.input_name.label }}

 

If you haven't set this yourself in forms.py Django will set this value as the name of your input field.

 

Get Label For Attribute

The for attribute allows users to click the label and focus on the corresponding input automatically.

 

for="{{ form.input_name.id_for_label }}"

 

Full Example

Here is a full example of building a form input an label manually in Django:

 

<label for="{{ form.example.id_for_label }}" class="form-label-full">{{ form.example.label }}</label>
<input type="date" name="{{ form.example.name }}" id="{{ form.example.auto_id }}" class="form-input form-input-w-full">
django