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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2021-10-15 11:00:00 +0000
Seen: 25 times
Last updated: Dec 18 '22
How can I set up Gunicorn with a Django Project?
How can I change the Django Admin Password?
How can mutual authentication be implemented on a development server for a Django web application?
What is the reason for the Django channels websocket resulting in a 404 error?
In Django, why are the fields from the parent class not included in the table of the child class?
How can we specify the database in which a model (table) should be created in Django?
Does the authenticate function in the Django Project always return "none"?
Where can I locate information about the inner workings and structure of Django?