Django Rest Framework - 如何为所有ModelSerializer字段创建自定义错误消息?

时间:2015-06-01 03:49:41

标签: django validation error-handling django-rest-framework django-serializer

这是我的serializers.py(我想为内置用户模型创建一个序列化程序):

from rest_framework import serializers

from django.contrib.auth.models import User

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('username', 'password', 'email', )

我知道Django Rest Framework拥有它自己的字段验证器,因为当我尝试使用已存在的用户名创建用户时,会引发错误说:

{'username': [u'This field must be unique.']}

我想自定义错误消息并说出"此用户名已被占用。请再试一次"而不是说"这个字段必须是唯一的"。

它还有一个内置的正则表达式验证器,因为当我创建带有感叹号的用户名时,它会说:

{'username': [u'Enter a valid username. This value may contain only letters, numbers and @/./+/-/_ characters.']}

我想自定义正则表达式验证程序,以便它只是说"用户名无效"。

如何自定义每个字段的所有错误消息?

注意:根据这篇文章:Custom error messages in Django Rest Framework serializer我能做到:

class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User

    def __init__(self, *args, **kwargs):
        super(UserSerializer, self).__init__(*args, **kwargs)

        self.fields['username'].error_messages['required'] = u'My custom required msg'

但是我该如何为这个独特的'和'正则表达式'验证?我试着做了

self.fields['username'].error_messages['regex'] = u'My custom required msg'

self.fields['username'].error_messages['validators'] = u'My custom required msg'

但都没有奏效。

1 个答案:

答案 0 :(得分:5)

要替换唯一或正则表达式错误消息,您应该更改相应验证程序对象的message成员。这可以使用单独的mixin类来完成:

from django.core.validators import RegexValidator
from rest_framework.validators import UniqueValidator
from django.utils.translation import ugettext_lazy as _


class SetCustomErrorMessagesMixin:
    """
    Replaces built-in validator messages with messages, defined in Meta class. 
    This mixin should be inherited before the actual Serializer class in order to call __init__ method.

    Example of Meta class:

    >>> class Meta:
    >>>     model = User
    >>>     fields = ('url', 'username', 'email', 'groups')
    >>>     custom_error_messages_for_validators = {
    >>>         'username': {
    >>>             UniqueValidator: _('This username is already taken. Please, try again'),
    >>>             RegexValidator: _('Invalid username')
    >>>         }
    >>>     }
    """
    def __init__(self, *args, **kwargs):
        # noinspection PyArgumentList
        super(SetCustomErrorMessagesMixin, self).__init__(*args, **kwargs)
        self.replace_validators_messages()

    def replace_validators_messages(self):
        for field_name, validators_lookup in self.custom_error_messages_for_validators.items():
            # noinspection PyUnresolvedReferences
            for validator in self.fields[field_name].validators:
                if type(validator) in validators_lookup:
                    validator.message = validators_lookup[type(validator)]

    @property
    def custom_error_messages_for_validators(self):
        meta = getattr(self, 'Meta', None)
        return getattr(meta, 'custom_error_messages_for_validators', {})

然后你可以继承这个mixin并更新Meta类:

class UserSerializer(SetCustomErrorMessagesMixin, serializers.HyperlinkedModelSerializer):
    class Meta:
        model = User
        fields = ('url', 'username', 'email', 'groups')
        custom_error_messages_for_validators = {
            'username': {
                UniqueValidator: _('This username is already taken. Please, try again'),
                RegexValidator: _('Invalid username')
            }
        }