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

时间:2013-11-04 15:08:55

标签: 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中的错误吗?

2 个答案:

答案 0 :(得分:5)

您所做的实施仅适用于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']

答案 1 :(得分:0)

它对我有用,所以继续尝试以下内容:

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