DjangoRestFramework似乎以各种方式处理错误。序列化程序类中的ValidationError不会始终如一地返回JSON。
当前响应包括JSON列表/对象字符串:
{"detail":["Unable to log in with provided credentials."]}
希望实现:
{"detail":"Unable to log in with provided credentials."}
我意识到这个响应是默认函数的结果。但是,我已经覆盖了验证功能:
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
views.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."}
答案 0 :(得分:0)
也许你应该尝试重写json渲染器类并连接一个自定义类,在那里你可以检查响应数据中的状态代码和detail
键,然后适当地重新格式化值。
我从来没有尝试过,所以我不能给你确切的代码库,但这是我能想到的唯一一种能够获得一致响应的方法。