Django REST Framework在序列化器中引发验证错误时如何指定错误代码 [英] Django REST Framework how to specify error code when raising validation error in serializer

查看:266
本文介绍了Django REST Framework在序列化器中引发验证错误时如何指定错误代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个API端点,该端点允许用户注册帐户。我想返回HTTP 409而不是400作为重复的用户名。

I have an API endpoint that allow users to register an account. I would like to return HTTP 409 instead of 400 for a duplicate username.

这是我的序列化器:

from django.contrib.auth.models import User
from rest_framework.serializers import ModelSerializer

class UserSerializer(ModelSerializer):
    username = CharField()

    def validate_username(self, value):
        if User.objects.filter(username=value).exists():
            raise NameDuplicationError()
        return value


class NameDuplicationError(APIException):
    status_code = status.HTTP_409_CONFLICT
    default_detail = u'Duplicate Username'

触发错误时,响应为: { detail: Duplicate Username} 。我意识到,如果我子类化APIException,将使用键 detail 代替 username

When the error is triggered, the response is: {"detail":"Duplicate Username"}. I realised that if I subclass APIException, the key detail is used instead of username.

我想获得此响应,而不是 { username: Duplicate Username}

I want to have this response instead {"username":"Duplicate Username"}

或者在引发ValidationError时我想指定一个状态代码:

or I would like to specify a status code when raising a ValidationError:

def validate_username(self, value):
    if User.objects.filter(username=value).exists():
        raise serializers.ValidationError('Duplicate Username', 
                                          status_code=status.HTTP_409_CONFLICT)
    return value

但这不起作用,因为 ValidationError 仅返回400。

But this does not work as ValidationError only returns 400.

还有其他方法可以做到这一点吗?

Is there any other way to accomplish this?

推荐答案

您可以引发其他异常,例如:

You can raise different exceptions like:

from rest_framework.exceptions import APIException
from django.utils.encoding import force_text
from rest_framework import status


class CustomValidation(APIException):
    status_code = status.HTTP_500_INTERNAL_SERVER_ERROR
    default_detail = 'A server error occurred.'

    def __init__(self, detail, field, status_code):
        if status_code is not None:self.status_code = status_code
        if detail is not None:
            self.detail = {field: force_text(detail)}
        else: self.detail = {'detail': force_text(self.default_detail)}

您可以在序列化程序中使用它,例如:

you can use this in your serializer like:

raise CustomValidation('Duplicate Username','username', status_code=status.HTTP_409_CONFLICT)

raise CustomValidation('Access denied','username', status_code=status.HTTP_403_FORBIDDEN)

这篇关于Django REST Framework在序列化器中引发验证错误时如何指定错误代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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