【问题标题】:Displaying errors at the top of the page in order of the fields按字段顺序在页面顶部显示错误
【发布时间】:2012-05-03 03:31:17
【问题描述】:

有了这个简单的模型

class Publisher(models.Model):
    name = models.CharField(max_length = 40)
    website = models.URLField()

    def __unicode__(self):
        return self.name

还有一个模型表格

class PublisherForm(ModelForm):

    class Meta:
        model = Publisher

更新模型

class PublisherForm(ModelForm):
    error_css_class = "error"   #class is applied if the field throws an error.
    required_css_class = "required" #outputs the cell with the class if the field is required

    def __init__(self, *args, **kwargs):
        super(PublisherForm, self).__init__(*args, **kwargs)
        self.fields.keyOrder = ['name', 'website']

    class Meta:
        model = Publisher

self.fields.keyOrder 对错误消息的顺序没有影响。它只会改变字段的顺序。

form.as_table生成的字段的顺序是按照在模型中声明的顺序

我在 shell 中运行了这段代码

from booksapp import models
>>> f = models.PublisherForm({})
>>> f.is_valid()
False
>>> f.as_table()
u'<tr class="required error"><th><label for="id_name">Name:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input id="id_name" type="text" name="name" maxlength="40" /></td></tr>\n<tr class="required error"><th><label for="id_website">Website:</label></th><td><ul class="errorlist"><li>This field is required.</li></ul><input id="id_website" type="text" name="website" maxlength="200" /></td></tr>'
>>> f.errors
{'website': [u'This field is required.'], 'name': [u'This field is required.']}
>>> 

根据模型,这里的 html 顺序是正确的,但错误的顺序不是。我认为名字应该放在第一位。

如果我需要在表单上方输出错误而不是内联,这将是一个问题。

如何让错误信息的顺序与模型中的字段顺序一致?如果您必须在顶部显示错误消息,您会怎么做?

【问题讨论】:

    标签: django


    【解决方案1】:

    您需要go through the form's data to get the field order,然后访问错误字典的相应元素。

    【讨论】:

    • 它对错误消息的顺序没有影响。它确实改变了字段的顺序。有什么方法可以按照与字段相同的顺序显示错误消息?
    • 我需要知道你尝试了什么,这样我才能告诉你你做错了什么。
    • 我在 PublisherForm 模型表单中添加了 init 方法,并在 shell 中执行了相同的命令。
    • 你是如何访问字典的?
    • 我做了一个 for 循环 - for error in f.errors: print f[error].errors
    猜你喜欢
    • 1970-01-01
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 2021-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多