2012-04-22 81 views
0

的順序有了這個簡單的模型顯示在頁面的頂部誤差在田裏

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 

自我.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

您需要go through the form's data to get the field order,然後才能訪問錯誤字典的相應元素。

+0

它對錯誤消息的順序沒有影響。它確實改變了字段的順序。以任何方式顯示錯誤消息的順序與字段相同? – iJK 2012-04-22 03:59:29

+0

我需要知道你所嘗試的,所以我可以告訴你你做錯了什麼。 – 2012-04-22 04:02:08

+0

我將__init__方法添加到PublisherForm模型窗體並在shell中執行相同的命令。 – iJK 2012-04-22 04:14:11