2

私はジャンゴ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)

clean_screening_formatsメソッドを持つ FilmShow のカスタム管理フォームを作成しました。

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 docsから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 に答える