Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
979 views
in Technique[技术] by (71.8m points)

django - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...