按字段顺序在页面顶部显示错误

时间:2012-04-22 03:33:12

标签: django

使用这个简单的模型

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的顺序根据模型是正确的,但错误的顺序不是。我认为这个名字应该是第一位的。

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

如何使错误消息的顺序与模型中的字段相同?如果您必须在顶部显示错误消息,该怎么办?

1 个答案:

答案 0 :(得分:1)

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