Django:如何输出段落<p>中的error_message而不是列表</p> <li>格式</li>

时间:2014-09-22 19:47:55

标签: django django-forms

我有一个简单的表单,它使用SessionWizardView将其分布在多个页面上。以下是其中一个问题的示例。

first_name = forms.CharField(max_length=100, label='What is your first name?', error_messages={'required': 'Please enter your first name'})

将其呈现为

<label for="id_0-first_name">What is your first Name?</label>
<ul class="errorlist">
    <li>Please enter your first name</li>
</ul>
<input id="id_0-first_name" maxlength="100" name="0-first_name" type="text" />

有人可以告诉我hwo更改错误输出,使其处于<p></p>格式而不是<li>列表项</li>格式吗?

我正在使用Django 1.6.2

2 个答案:

答案 0 :(得分:1)

您必须创建一个可以根据需要呈现HTML的类。请参阅docs here

文档中的示例:

from django.forms.util import ErrorList
class DivErrorList(ErrorList):
    def __unicode__(self):
        return self.as_divs()
    def as_divs(self):
        if not self: return u''
        return u'<div class="errorlist">%s</div>' % ''.join([u'<div class="error">%s</div>' % e for e in self])
f = ContactForm(data, auto_id=False, error_class=DivErrorList)
f.as_p()

答案 1 :(得分:1)

您可以像@schillingt建议的那样创建自己的错误列表类。

或者,如果您想在模板中处理此问题,可以使用以下内容:

<form method="post" action="/some-view/">
    ... other fields, etc. omitted ...

    <!-- The label and form field -->
    {{ form.first_name.label_tag }}
    {{ form.first_name }}

    <!-- Output any errors -->
    {% for error in form.first_name.errors %}
        <p>{{ error }}</p>
    {% endfor %}

    ... other fields, etc. omitted ...

    <button type="submit">Submit</button>

</form>

更新

为了以完全可重复的方式执行此操作,请创建名为form-field.html的模板:

    {{ field.label_tag }}
    {{ field }}

    <!-- Output any errors -->
    {% for error in field.errors %}
        <p>{{ error }}</p>
    {% endfor %}

然后,更新您的主模板:

<form method="post" action="/some-view/">
    ... other fields, etc. omitted ...

    {% with field=form.first_name %}
        {% include "form-field.html" %}
    {% endwith %}

    ... other fields, etc. omitted ...

    <button type="submit">Submit</button>

</form>

然后,您可以对单个form-field.html模板进行更新并更新所有表单,这会使您的主模板更简单