2017-10-06 134 views
0

使用DRF创建简单的登录API时,我遇到了一个问题。登录需要两个字段emailpassword。如果字段为空如下所示json消息:DRF:自定义字段错误消息

{ 
    "email": [ 
     "This field may not be blank." 
    ], 
    "password": [ 
     "This field may not be blank." 
    ] 
} 

但我想自定义错误消息,说喜欢的东西,

{ 
    "email": [ 
     "Email field may not be blank." 
    ], 
    "password": [ 
     "Password field may not be blank." 
    ] 
} 

我试图像在validate()以下在serializers.py

if email is None: 
      raise serializers.ValidationError(
       'An email address is required to log in.' 
      ) 

但它没有得到override,我不知道这是什么缘故。

编辑

我@dima回答它仍然无法正常工作落实。我在做什么错了?现在我的串行的样子:

class LoginSerializer(serializers.Serializer): 
    email = serializers.CharField(max_length=255, required=True, error_messages={"required": "Email field may not be blank."}) 
    username = serializers.CharField(max_length=255, read_only=True) 
    password = serializers.CharField(max_length=128, write_only=True, required=True, 
     error_messages={"required": "Password field may not be blank."}) 
    token = serializers.CharField(max_length=255, read_only=True) 

    def validate(self, data): 
     # The `validate` method is where we make sure that the current 
     # instance of `LoginSerializer` has "valid". In the case of logging a 
     # user in, this means validating that they've provided an email 
     # and password and that this combination matches one of the users in 
     # our database. 
     email = data.get('email', None) 
     password = data.get('password', None) 
     user = authenticate(username=email, password=password) 

     # If no user was found matching this email/password combination then 
     # `authenticate` will return `None`. Raise an exception in this case. 
     if user is None: 
      raise serializers.ValidationError(
       'A user with this email and password was not found.' 
      ) 

     # Django provides a flag on our `User` model called `is_active`. The 
     # purpose of this flag is to tell us whether the user has been banned 
     # or deactivated. This will almost never be the case, but 
     # it is worth checking. Raise an exception in this case. 
     if not user.is_active: 
      raise serializers.ValidationError(
       'This user has been deactivated.' 
      ) 

     # The `validate` method should return a dictionary of validated data. 
     # This is the data that is passed to the `create` and `update` methods 
     # that we will see later on. 
     return { 
      'email': user.email, 
      'username': user.username, 
      'token': user.token 
     } 

views.py

class AuthLogin(APIView): 
    ''' Manual implementation of login method ''' 

    permission_classes = (AllowAny,) 
    serializer_class = LoginSerializer 

    def post(self, request, *args, **kwargs): 
     data = request.data 
     serializer = LoginSerializer(data=data) 
     if serializer.is_valid(raise_exception=True): 
      new_data = serializer.data 
      return Response(new_data) 
     return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) 

回答

1

你需要field-level-validation,试试吧:

def validate_email(self, value): 
#   ^^^^^^ 
    if not value: 
     raise serializers.ValidationError(
      'An email address is required to log in.' 
     ) 
    return value 
2

可以设置error_messages属性,用于要覆盖消息的字段。你的情况:

class LoginSerializer(serializers.Serializer): 
    email = serializers.CharField(max_length=255, required=True, error_messages={"required": "Email field may not be blank."}) 
    username = serializers.CharField(max_length=255, read_only=True) 
    password = serializers.CharField(max_length=128, write_only=True, required=True, error_messages={"required": "Password field may not be blank."}) 
    token = serializers.CharField(max_length=255, read_only=True) 

对于ModelSerializers你能在元级使用该财产extra_kwargs

class SomeModelSerializer(serializers.ModelSerializer): 
    class Meta: 
     model = SomeModel 
     fields = ('email', 'password') 
     extra_kwargs = { 
      'password': {"error_messages": {"required": "Password field may not be blank."}}, 
      'email': {"error_messages": {"required": "Email field may not be blank."}}, 
     } 
+0

我编辑了这篇文章,现在我的'serializer'看起来像上面那样。按照你的建议,不知道我做错了什么。请帮助 –

+0

我编辑了我的答案,它不起作用,因为您使用'Serializer'而不是'ModelSerializer' –

+0

仍然无法正常工作。 :( –