django form label in template
To add a label to a Django form in a template, follow these steps:
- In your Django form class, define a label for each field using the
label
attribute. For example:
from django import forms
class MyForm(forms.Form):
field1 = forms.CharField(label='Field 1')
field2 = forms.CharField(label='Field 2')
- In your template, render the form using the
{{ form }}
template variable. For example:
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
- By default, Django will use the field name as the label. If you want to display a different label, you can access it in the template using the
{{ form.field.label }}
template variable. For example:
<form method="post">
{% csrf_token %}
<label for="{{ form.field1.id_for_label }}">{{ form.field1.label }}</label>
{{ form.field1 }}
<label for="{{ form.field2.id_for_label }}">{{ form.field2.label }}</label>
{{ form.field2 }}
<button type="submit">Submit</button>
</form>
- In the above example, we access the label for each field using
{{ form.field1.label }}
and{{ form.field2.label }}
. We also use{{ form.field1 }}
and{{ form.field2 }}
to render the form input fields.
By following these steps, you can add labels to Django form fields in your template.