如何更改DjangoRestFramework序列化程序的“此字段是必需的”错误消息?

时间:2015-09-29 04:51:14

标签: django django-rest-framework django-serializer

当用户通过JSON用户对象向后端提交表单时,这是处理它的视图:

public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('first_name', 80);
            $table->string('last_name', 80);
            $table->string('email')->unique();
            $table->string('mobile',80);
            $table->string('password', 60);
            $table->boolean('confirmed')->default(0);
            $table->string('confirmation_code')->nullable();
            $table->float('amount', 80);
            $table->rememberToken();
            $table->timestamps();
        });
    } 

我的问题是,如果用户没有填写表单中的某个字段,DRF发送给前端的错误消息是“此字段是必需的”。有没有办法让我更改它,以便对于所有字段,错误消息是“{fieldname}是必需的。”?

这是我的serializers.py:

class user_list(APIView):
    """
    Create a new user.
    """

    def post(self, request):
        serializer = UserSerializer(data=request.DATA)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

这是SetCustomErrorMessageMixin:

from rest_framework import serializers
from django.contrib.auth.models import User
from CMSApp.mixins import SetCustomErrorMessagesMixin

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


class UserSerializer(SetCustomErrorMessagesMixin, serializers.ModelSerializer):

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

        extra_kwargs = {
                    'password': {
                        'write_only': True,
                    }
                }

        custom_error_messages_for_validators = {
            'username': {
                UniqueValidator: _('This username is already taken. Please try again.'),
                RegexValidator: _('Invalid username')
            }
        }

    def create(self, validated_data):
        user = User.objects.create_user(
            email = validated_data['email'],
            username = validated_data['username'],
            password = validated_data['password'],
        )
        return user

最后,这是我的models.py(UserExtended模型):

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', {})

1 个答案:

答案 0 :(得分:7)

您可以覆盖__init__() UserSerializer方法来更改required字段的默认错误消息。

我们将遍历序列化程序的fields并更改error_messages密钥的默认required值。

class UserSerializer(SetCustomErrorMessagesMixin, serializers.ModelSerializer):

    def __init__(self, *args, **kwargs):
        super(UserSerializer, self).__init__(*args, **kwargs) # call the super() 
        for field in self.fields: # iterate over the serializer fields
            self.fields[field].error_messages['required'] = '%s field is required'%field # set the custom error message

    ...