Django Rest Framework自定义验证错误 [英] Django Rest Framework custom validation errors

查看:276
本文介绍了Django Rest Framework自定义验证错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为帐户模型自定义DRF(3.x)的默认验证错误。
我的目标是编写验证函数,以便发送回自定义的错误消息。



我尝试了以下操作:

 类AccountSerializer(serializers.ModelSerializer):
密码= serializers.CharField(write_only = True,必填= False)

类元:
模型=帐户
字段=('id','email','password',)

def validate_password(self,value):

验证密码。

如果没有输入值:
提高serializers.ValidationError(密码不能为空!)
elif len (值)< 5:
引发serializers.ValidationError( Password to short ...)
返回值

长度验证工作正常,但是永远不会抛出密码为空验证,因为之前已经抛出了默认错误(密码,[u'此字段可能不为空。)。 / p>

是否有任何选项可以禁用默认错误或首先通过我的自定义功能强制进行验证?



感谢帮助!

解决方案

您可以通过设置初始化字段时, error_messages 参数。您需要传递一个词典,键为错误消息名称,值为错误消息的自定义文本。



在您的情况下,您希望实施两个错误消息: 必需 min_length 。您可能还需要覆盖 blank ,这会触发您当前的错误,除非您在字段上设置 allow_blank = True



因此,通过这些更改,您的序列化器将变为

  class AccountSerializer(serializers.ModelSerializer):
密码= serializers.CharField(
write_only = True,
required = False,
min_length = 5,
error_messages = {
blank:密码不能为空。 ,
min_length:密码太短。,
},


类元:
模型=帐户
字段=('id','email','password',)

我已替换了您的 len 密码字段上的 min_length 参数



这会将您所有的验证工作卸载到Django REST框架,这将使将来的升级变得更加容易。如果需要其他自定义验证,您仍然可以覆盖 validate_password ,但是由于它为空,因此我现在将其删除。


I'm trying to customize the default validation errors of DRF (3.x) for an account model. My goal is to write a validation function in order to send back a customized error message.

I've tried the following:

class AccountSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, required=False)

    class Meta:
        model = Account
        fields = ('id', 'email', 'password',)

    def validate_password(self, value):
        """
        Validate Password.
        """
        if not value:
            raise serializers.ValidationError("Password cannot be empty!")
        elif len(value) < 5:
            raise serializers.ValidationError("Password to short...")
        return value

The the length validation works fine, but the 'password is empty' validation is never thrown because the default error ('password', [u'This field may not be blank.']) is thrown before.

Is there any option to disable default errors or to force validation by my custom function first?

Thanks for help!

解决方案

You can override the validation errors on a per-field basis by setting the error_messages argument when initializing the field. You need to pass a dictionary with the key being the error message name, and the value being the custom text for the error message.

In your case, you are looking to implement two error messages: required and min_length. You may also need to override blank, which is triggering your current error, unless you set allow_blank=True on the field.

So with those changes, your serializer would become

class AccountSerializer(serializers.ModelSerializer):
    password = serializers.CharField(
        write_only=True,
        required=False,
        min_length=5,
        error_messages={
            "blank": "Password cannot be empty.",
            "min_length": "Password too short.",
        },
    )

    class Meta:
        model = Account
        fields = ('id', 'email', 'password', )

I've replaced your len check with the min_length argument on the password field.

This offloads all of your validation to Django REST framework, which should make upgrades easier in the future. You can still override validate_password if you need additional custom validation, but for now I've removed it since it would be empty.

这篇关于Django Rest Framework自定义验证错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆