如何渲染 Django 表单错误而不是在 UL 中?

发布于 2024-12-04 08:20:55 字数 668 浏览 0 评论 0原文

我的 Django 表单中的错误按照 docs 在 UL 中呈现...

Django

{{ form.non_field_errors }}

HTML

<ul class="errorlist">
  <li>Sender is required.</li>
</ul>

如何我可以呈现错误,使它们不出现在 UL 中,而是出现在每个字段相关错误的段落标记中吗?所以理想情况下...

<ul>
  <li>
    <label>...</label>
    <input>...</input>
    <p>Error message...</p>
  </li>
</ul>

编辑:

为了清楚起见,我应该在我的示例中使用此代码...

{{ form.fieldname.errors }}

The errors in my Django form are rendering in a UL as per the docs...

Django

{{ form.non_field_errors }}

HTML

<ul class="errorlist">
  <li>Sender is required.</li>
</ul>

How can I render the errors so they appear not in a UL, but in a paragraph tag for each fields relevant error? So ideally...

<ul>
  <li>
    <label>...</label>
    <input>...</input>
    <p>Error message...</p>
  </li>
</ul>

EDIT:

I should have used this code in my example for clarity...

{{ form.fieldname.errors }}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

姐不稀罕 2024-12-11 08:20:55

您可以在模板中显示错误,如下所示:

<p>{{ form.fieldname.errors.as_text }}</p>

You can display your error as the following in your template:

<p>{{ form.fieldname.errors.as_text }}</p>

它显然无法在字段的上下文中呈现,因为正如属性名称所暗示的那样,这些是“非字段错误”。解决此问题的唯一方法是在验证时在正确的位置添加错误。例如,执行以下操作会导致非字段错误:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def clean(self):
        somefield = self.cleaned_data.get('somefield')
        if not somefield:
            raise forms.ValidationError('Some field is blank')

但是,您可以执行以下操作以使该错误仍然显示在右侧字段上:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def clean(self):
        somefield = self.cleaned_data.get('somefield')
        if not somefield:
            if not self._errors.has_key('somefield'):
                from django.forms.util import ErrorList
                self._errors['somefield'] = ErrorList()
            self._errors['somefield'].append('Some field is blank')

更新:

来自 Django 文档

每个命名的表单字段都可以使用 {{
form.name_of_field }},这将生成显示所需的 HTML
表单小部件。使用 {{ form.name_of_field.errors }} 显示列表
表单错误,呈现为无序列表。这可能看起来像:

<ul class="errorlist">
    <li>Sender is required.</li>
</ul>

该列表有一个 CSS 类 errorlist,允许您设置其样式
外貌。 如果您希望进一步自定义错误的显示,您可以
可以通过循环它们来做到这一点(强调我的)

{% if form.subject.errors %}
    <ol>
    {% for error in form.subject.errors %}
        <li><strong>{{ error|escape }}</strong></li>
    {% endfor %}
    </ol>
{% endif %}

It obviously can't render within the context of the field because these are "non-field errors" as the attribute name implies. The only way to fix this is to add the error in the right place when validating. For example, doing the following results in non-field errors:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def clean(self):
        somefield = self.cleaned_data.get('somefield')
        if not somefield:
            raise forms.ValidationError('Some field is blank')

However, you can do the following to make that error still show on the right field:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel

    def clean(self):
        somefield = self.cleaned_data.get('somefield')
        if not somefield:
            if not self._errors.has_key('somefield'):
                from django.forms.util import ErrorList
                self._errors['somefield'] = ErrorList()
            self._errors['somefield'].append('Some field is blank')

UPDATE:

From the Django docs:

Each named form-field can be output to the template using {{
form.name_of_field }}, which will produce the HTML needed to display
the form widget. Using {{ form.name_of_field.errors }} displays a list
of form errors, rendered as an unordered list. This might look like:

<ul class="errorlist">
    <li>Sender is required.</li>
</ul>

The list has a CSS class of errorlist to allow you to style its
appearance. If you wish to further customize the display of errors you
can do so by looping over them (emphasis mine)
:

{% if form.subject.errors %}
    <ol>
    {% for error in form.subject.errors %}
        <li><strong>{{ error|escape }}</strong></li>
    {% endfor %}
    </ol>
{% endif %}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文