Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to render form field with information that it is required

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.

like image 586
gruszczy Avatar asked Aug 10 '09 10:08

gruszczy


People also ask

What is form AS_P in Django?

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.

What are forms explain different form fields?

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.

What is form Django?

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.


1 Answers

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.

like image 170
Vebjorn Ljosa Avatar answered Sep 28 '22 11:09

Vebjorn Ljosa