Ask Your Question
3

How can a red asterisk (*) be shown in Django forms?

asked 2021-10-15 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-12-18 11:00:00 +0000

qstack gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2021-10-15 11:00:00 +0000

Seen: 25 times

Last updated: Dec 18 '22