我想更改 JSON,当发生验证错误时,rest_framework 或 Django 返回该 JSON。
我将使用我的视图之一作为示例,但我想更改所有视图的错误消息。假设我有这个视图,旨在登录用户,提供电子邮件和密码。如果这些正确,它将返回 access_token。
如果我只发布密码,它会返回错误 400:
{"email": ["This field is required."]}
如果密码和电子邮件不匹配:
{"detail": ["Unable to log in with provided credentials."]}
我想要的更像是:
{"errors": [{"field": "email", "message": "This field is required."}]}
{"errors": [{"non-field-error": "Unable to log in with provided credentials."}]}
现在这是我的view:
class OurLoginObtainAuthToken(APIView):
permission_classes = (AllowAny,)
serializer_class = serializers.AuthTokenSerializer
model = Token
def post(self, request):
serializer = self.serializer_class(data=request.DATA)
if serializer.is_valid():
#some magic
return Response(token)
return Response(serializers.errors, status=status.HTTP_400_BAD_REQUEST)
我可以访问序列化器错误并改变它们,但看起来像只能通过这种方式访问字段错误,如何更改在我的序列化器的验证方法中创建的验证错误?
这是我的串行器(它与相同的序列化器rest_framework.authtoken.serializers.AuthTokenSerializer
)但已编辑,因此身份验证不需要用户名而是电子邮件:
class AuthTokenSerializer(serializers.Serializer):
email = serializers.CharField()
password = serializers.CharField()
def validate(self, attrs):
email = attrs.get('email')
password = attrs.get('password')
if email and password:
user = authenticate(email=email, password=password)
if user:
if not user.is_active:
msg = _('User account is disabled.')
raise ValidationError(msg)
attrs['user'] = user
return attrs
else:
msg = _('Unable to log in with provided credentials.')
raise ValidationError(msg)
else:
msg = _('Must include "username" and "password"')
raise ValidationError(msg)
或者也许有一种完全不同的方法?我将非常感谢任何想法。