【发布时间】:2010-11-11 22:18:14
【问题描述】:
Django Forms 框架非常出色,只需以下方式即可呈现整个表单。
{{ form.as_p }}
对于注册表,它将上面转换为:
<p><label for="id_username">Username:</label> <input id="id_username" type="text" name="username" maxlength="30" /> Required. 30 characters or fewer. Alphanumeric characters only (letters, digits and underscores).</p>
<p><label for="id_email">Email:</label> <input type="text" name="email" id="id_email" /></p>
<p><label for="id_firstname">Firstname:</label> <input type="text" name="firstname" id="id_firstname" /></p>
<p><label for="id_lastname">Lastname:</label> <input type="text" name="lastname" id="id_lastname" /></p>
<p><label for="id_password1">Password:</label> <input type="password" name="password1" id="id_password1" /></p>
<p><label for="id_password2">Password confirmation:</label> <input type="password" name="password2" id="id_password2" /></p>
但是为了设计我想给表单中的每个元素添加类,如下:
<p><label for="id_email" class="field-title">Email:</label> <input type="text" name="email" id="id_email" /></p>
<p><label for="id_firstname" class="field-title">Firstname:</label> <input type="text" name="firstname" id="id_firstname" /></p>
<p><label for="id_lastname" class="field-title">Lastname:</label> <input type="text" name="lastname" id="id_lastname" /></p>
<p><label for="id_password1" class="field-title">Password:</label> <input type="password" name="password1" id="id_password1" /></p>
<p><label for="id_password2" class="field-title">Password confirmation:</label> <input type="password" name="password2" id="id_password2" /></p>
将这些类添加到单个表单元素的标准方法是什么。是否需要在模板中手动展开表单来添加这些类(这种情况下,表单的变化也要在模板中做出相应的变化);这太费力了,特别是因为您需要为每个字段添加 if 错误、显示错误。
或者从表单类或视图中提供一些类更好,这看起来有点难看。
我不太了解 css,应该可以在给定的表单类中为指定的标签定义这些类。如果是,这应该是最好的方法。
如何将设计器类添加到表单元素。您认为添加它们的最佳方式是什么。
【问题讨论】:
标签: css django forms templates