2

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

4

2 回答 2

6

您所做的实现仅在 Django 1.6+ 中有效。比较:1.6 文档1.5

在 1.6 之前,消息会立即转换为字符串django.core.exceptions.ValidationError(请参见此处的代码):

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']
于 2013-11-04T18:57:24.423 回答
0

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

def clean(self):
if self.acci_anios_residencia == None:
    lista = ["Especifique un año"]
    raise ValidationError({'acci_anios_residencia': lista})
于 2016-02-01T04:39:32.610 回答