DjangoRestFramework 似乎以多种方式处理错误。序列化程序类中的 ValidationError 不会始终返回相同的 JSON。
当前响应包括一个 JSON 列表/对象字符串:
{"detail":["Unable to log in with provided credentials."]}
期待实现:
{"detail":"Unable to log in with provided credentials."}
我意识到这个响应是默认函数的结果。但是,我已经覆盖了 validate 函数:
class AuthCustomTokenSerializer(serializers.Serializer):
username = serializers.CharField(write_only=True)
password = serializers.CharField(write_only=True)
token = serializers.CharField(read_only=True)
def validate(self, validated_data):
username = validated_data.get('username')
password = validated_data.get('password')
# raise serializers.ValidationError({'detail': 'Unable to log in with provided credentials.'})
if username and password:
user = authenticate(phone_number=username, password=password)
try:
if UserInfo.objects.get(phone_number=username):
userinfo = UserInfo.objects.get(phone_number=username)
user = User.objects.filter(user=userinfo.user, password=password).latest('date_joined')
if user:
if user.is_active:
validated_data['user'] = user
return validated_data
else:
raise serializers.ValidationError({"detail": "User account disabled."})
except UserInfo.DoesNotExist:
try:
user = User.objects.filter(email=username, password=password).latest('date_joined')
if user.is_active:
validated_data['user'] = user
return validated_data
except User.DoesNotExist:
#raise serializers.ValidationError("s")
raise serializers.ValidationError({'detail': 'Unable to log in with provided credentials.'})
else:
raise serializers.ValidationError({"detail" : "Must include username and password."})
class Meta:
model = Token
fields = ("username", "password", "token")
我尝试添加自定义异常处理程序:
from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first,
# to get the standard error response.
response = exception_handler(exc, context)
# Now add the HTTP status code to the response.
if response is not None:
response.data['status_code'] = response.status_code
return response
视图.py:if serializer.is_valid(raise_exception=True):
但是,这只会附加当前引发的错误:
{"detail":["Unable to log in with provided credentials."],"status_code":400}
我应该如何使用更改返回文本的格式?它只在 validate 函数中为这个特定的序列化程序返回这样的 JSON。
我还研究了格式化 non_field_errors 模板,但它适用于我的所有其他序列化程序,例如:
{"detail": "Account exists with email address."}