With this simple model
class Publisher(models.Model):
name = models.CharField(max_length = 40)
website = models.URLField()
def __unicode__(self):
return self.name
and a model form
class PublisherForm(ModelForm):
class Meta:
model = Publisher
Updated Model
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 has no effect on the order of the error messages. It only changes the order of the fields.
The order of the fields generated by form.as_table is in the order of them being declared in the model
I ran this code in the 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.']}
>>>
Here the order of the html is correct according to the model but the order of the errors is not. I think the name should come first.
This will be an issue if I need to output the errors above the form and not inline.
How to get the order of the error messages to be the same as the fields in the model? What do you do if you would have to display the error messages at the top?