如何使用需要的信息来呈现表单域 [英] How to render form field with information that it is required
问题描述
有没有什么聪明的方式来使django表单渲染字段与星号需要的字段后?还是提供一些其他聪明的标记所需字段?如果我已经按照表格中的要求设置了一个字段,那么我不想再在模板中执行。
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.
推荐答案
从Django 1.2开始,如果您的表单有一个名为 required_css_class
的属性,它将被添加到 BoundField.css_classes
中必填字段。然后,您可以使用CSS根据需要对表单的必需部分进行样式。一个典型的用例:
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>
如果您使用 Form.as_table()
, Form.as_ul
和 Form.as_p
,他们自动执行此操作,将类添加到< tr>
,< li>
和< p>
分别。
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.
这篇关于如何使用需要的信息来呈现表单域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!