【发布时间】:2013-11-15 05:56:43
【问题描述】:
我正在使用 django 1.5.5。对于我的项目。我有一些模型,其中一些与另一个具有多对多字段:
class ScreeningFormat(CorecrmModel):
name = models.CharField(max_length=100)
class Film(CorecrmModel):
title = models.CharField(max_length=255)
screening_formats = models.ManyToManyField(ScreeningFormat)
class Screen(CorecrmModel):
name = models.CharField(max_length=100)
screening_formats = models.ManyToManyField(ScreeningFormat)
class FilmShow(CorecrmModel):
film = models.ForeignKey(Film)
screen = models.ForeignKey(Screen)
screening_formats = models.ManyToManyField(ScreeningFormat)
我为 FilmShow 创建了一个自定义管理表单,其中包含 clean_screening_formats 方法:
class FilmShowAdminForm(admin.ModelForm):
def clean_screening_formats(self):
# Make sure the selected screening format exists in those marked for the film
screening_formats = self.cleaned_data['screening_formats']
film_formats = self.cleaned_data['film'].screening_formats.all()
sf_errors = []
for (counter, sf) in enumerate(screening_formats):
if sf not in film_formats:
sf_error = forms.ValidationError('%s is not a valid screening format for %s' % (sf.name, self.cleaned_data['film'].title), code='error%s' % counter)
sf_errors.append(sf_error)
if any(sf_errors):
raise forms.ValidationError(sf_errors)
return formats
实际的验证检查工作正常,但管理表单上这些错误消息的输出有点偏离。而单个错误消息输出为(例如):
This field is required.
消息列表的输出如下所示:
[u'35mm Film is not a valid screening format for Thor: The Dark World']
[u'Blu Ray is not a valid screening format for Thor: The Dark World']
谁能建议我如何使这些错误消息列表正确显示?
编辑: 我认为这个问题是由于 django 在引发多个错误时存储消息的方式略有不同。示例:
>>> from django import forms
>>> error = forms.ValidationError('This is the error message', code='lone_error')
>>> error.messages
[u'This is the error message']
>>> e1 = forms.ValidationError('This is the first error message', code='error1')
>>> e2 = forms.ValidationError('This is the second error message', code='error2')
>>> error_list = [e1, e2]
>>> el = forms.ValidationError(error_list)
>>> el.messages
[u"[u'This is the first error message']", u"[u'This is the second error message']"]
这可能是 Django 中的错误吗?
【问题讨论】:
-
澄清一下:您正在寻找字段级消息传递?
-
我想我有字段级消息,我只想知道如何为一个字段输出多个消息,而每个消息周围没有“[u'']”
-
能否贴出显示错误信息的模板部分?
-
我使用的是默认的 django 管理模板,所以错误列表是从
field.field.errors.as_ul模板标签构建的。我会用更多信息更新问题
标签: django django-forms django-admin django-validation