1 | initial version |
A red asterisk (*) can be shown in Django forms by using the HTML required
attribute on the form fields and then adding CSS styling to the label to display the asterisk.
Here's an example:
# forms.py
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(label='Name*', required=True)
email = forms.EmailField(label='Email*', required=True)
message = forms.CharField(label='Message*', required=True, widget=forms.Textarea)
# template.html
<form method="post" action="{% url 'contact' %}">
{% csrf_token %}
<div class="form-group">
{{ form.name.label_tag }} {{ form.name }}
</div>
<div class="form-group">
{{ form.email.label_tag }} {{ form.email }}
</div>
<div class="form-group">
{{ form.message.label_tag }} {{ form.message }}
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
# styles.css
label.required:after {
content: " *";
color: red;
}
In this example, the required
attribute is set to True
on the name, email, and message fields in the ContactForm
. In the template, we render the form fields and their labels using label_tag
and form_field
methods. Finally, in the styles.css
file, we add the :after
CSS pseudo-selector to the label.required
class to display the red asterisk.