Add help text in Django model forms
To add help text in Django model forms, follow these steps:
- Define the model field in your model class, and provide a
help_text
attribute with the desired help text.
from django.db import models
class MyModel(models.Model):
my_field = models.CharField(max_length=100, help_text="This is the help text.")
- Create a form class that inherits from
django.forms.ModelForm
ordjango.forms.Form
.
from django import forms
from .models import MyModel
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
fields = "__all__"
- In your template, render the form using the
{{ form }}
template variable.
<form method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
- (Optional) You can also display the help text next to the form field by iterating over the form's fields and using the
{{ field.help_text }}
template variable.
<form method="post">
{% csrf_token %}
{% for field in form %}
{{ field.label_tag }}: {{ field }}
<small>{{ field.help_text }}</small>
{% endfor %}
<input type="submit" value="Submit">
</form>
By following these steps, you can add help text to your Django model forms.