Django:正确显示一个字段的多个错误消息

标签 django django-forms django-admin django-validation

我使用的是 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 中的错误吗?

最佳答案

您所做的实现仅对 Django 1.6+ 有效。比较:1.6 docs1.5 .

在 1.6 之前,消息在 django.core.exceptions.ValidationError 中被立即转换为字符串(参见代码 here ):

class ValidationError(Exception):
    """An error while validating data."""
    def __init__(self, message, code=None, params=None):
        import operator
        from django.utils.encoding import force_text
        """
        ValidationError can be passed any object that can be printed (usually
        a string), a list of objects or a dictionary.
        """
        if isinstance(message, dict):
            self.message_dict = message
            # Reduce each list of messages into a single list.
            message = reduce(operator.add, message.values())

        if isinstance(message, list):
            self.messages = [force_text(msg) for msg in message]  #! Will output "u'<message>'"

在您的例子中,不是传递 ValidationError 实例列表,而是传递字符串列表:

>>> e1 = 'This is the first error message'
>>> e2 = 'This is the second error message'
>>> error_list = [e1, e2]
>>> el = forms.ValidationError(error_list)
>>> el.messages
[u'This is the first error message', u'This is the second error message']

关于Django:正确显示一个字段的多个错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19770705/

相关文章:

django - 为什么 TimeInput 的 Django 小部件不显示

python - 基于 django 类的 View get_context_data 得到了一个意外的关键字参数

python - Django 表单初始化方法失败

django - NGINX 502 错误网关 gunicorn 超时

django 从相关模型(外键)获取值

python - 如何在 django 管理站点中使用 django-select2 小部件?

python - Django 管理日期范围过滤器

django - 在 django admin 中显示使用 WYSIWYG 制作的内容时出现问题

python - 什么是基于 python 的好 Webshop 软件?

django - 在Model.Meta中与Django GenericForeignKey一起使用CheckConstraint时出错-此查询中不允许联接的字段引用