相关疑难解决方法(0)

Django Rest Framework自定义验证错误

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

我尝试过以下方法:

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
Run Code Online (Sandbox Code Playgroud)

长度验证工作正常,但'密码为空'验证永远不会被抛出,因为之前抛出了默认错误('密码',[这个字段可能不是空白.']).

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

感谢帮助!

validation field django-rest-framework

6
推荐指数
2
解决办法
7848
查看次数

Django-rest-framework 中的全局异常处理

有没有一种方法可以在不使用 django rest 框架中的 try-except 块的情况下全局处理所有异常。

我想将 django 抛出的 html 错误页面转换为自定义的 json 对象响应。

我在我的应用程序中创建了一个 exception.py 文件

def custom_exception_handler(exc, context=None):
    response = exception_handler(exc)


    if isinstance(exc, HttpResponseServerError):  
        custom_response_data = { 
            'detail': 'Internal Server Error' # custom exception message
        }
        response.data = custom_response_data

    return response
Run Code Online (Sandbox Code Playgroud)

我已经在 settings.py 中配置了这个。

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
'EXCEPTION_HANDLER':'my_project.my_app.exceptions.custom_exception_handler'}
Run Code Online (Sandbox Code Playgroud)

django exception django-errors django-rest-framework django-rest-viewsets

5
推荐指数
2
解决办法
5951
查看次数