Form.required_css_class
It’s pretty common to style form rows and fields that are required or have errors. For example, you might want to present required form rows in bold and highlight errors in red.
The Form
class has a couple of hooks you can use to add class
attributes to required rows or to rows with errors: simply set the Form.error_css_class
and/or Form.required_css_class
attributes:
from django.forms import Form class ContactForm(Form): error_css_class = 'error' required_css_class = 'required' # ... and the rest of your fields here
Once you’ve done that, rows will be given "error"
and/or "required"
classes, as needed. The HTML will look something like:
>>> f = ContactForm(data) >>> print(f.as_table()) <tr class="required"><th><label class="required" for="id_subject">Subject:</label> ... <tr class="required"><th><label class="required" for="id_message">Message:</label> ... <tr class="required error"><th><label class="required" for="id_sender">Sender:</label> ... <tr><th><label for="id_cc_myself">Cc myself:<label> ... >>> f['subject'].label_tag() <label class="required" for="id_subject">Subject:</label> >>> f['subject'].label_tag(attrs={'class': 'foo'}) <label for="id_subject" class="foo required">Subject:</label>
Please login to continue.