【问题标题】:Django: correctly display multiple error messages for one fieldDjango:为一个字段正确显示多条错误消息
【发布时间】: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


【解决方案1】:

您所做的实现仅从 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']

【讨论】:

    【解决方案2】:

    它对我有用,所以请继续尝试以下方法:

    def clean(self):
    if self.acci_anios_residencia == None:
        lista = ["Especifique un año"]
        raise ValidationError({'acci_anios_residencia': lista})
    

    【讨论】:

      猜你喜欢
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 2017-03-31
      • 2018-05-25
      • 1970-01-01
      • 1970-01-01
      • 2011-09-21
      • 1970-01-01
      相关资源
      最近更新 更多