Is there any clever way to make django forms render field with asterisks after fields that are required? Or to provide some other clever for to mark required fields? I wouldn't like to have to do it again in a template if I already set a field as required in the form.
as_p simply wraps all the elements in HTML <p> tags. The advantage is not having to write a loop in the template to explicitly add HTML to surround each title and field. There is also form. as_table and form. as_ul to also help set the form within the HTML context you wish.
The form body contains Field elements that define how each element of the Web page appears and behaves. Each Field can contain other fields, each with its own display component. Form fields comprise several parts, which are encapsulated by the <Field> tag set: Value Expressions.
The Django Form class (A ModelForm maps a model class's fields to HTML form <input> elements via a Form ; this is what the Django admin is based upon.) A form's fields are themselves classes; they manage form data and perform validation when a form is submitted.
As of Django 1.2, if your form has an attribute named required_css_class
, it will be added to BoundField.css_classes
for required fields. You can then use CSS to style the required parts of the form as desired. A typical use case:
# views.py class MyForm(django.forms.Form): required_css_class = 'required' …
…
/* CSS */ th.required { font-weight: bold; }
…
<!-- HTML --> <tr> <th class="{{form.name.css_classes}}">{{form.name.label_tag}}</th> <td>{{form.name.errors}}{{form.name}}</td> </tr>
If you use Form.as_table()
, Form.as_ul
, and Form.as_p
, they do this automatically, adding the class to <tr>
, <li>
, and <p>
, respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With