Tôi muốn thay đổi JSON, mà rest_framework hoặc django trả về khi một lỗi xác nhận xảy ra.Làm cách nào để thay đổi phản hồi lỗi xác thực trong DRF?
Tôi sẽ sử dụng một trong các chế độ xem của mình làm ví dụ, nhưng tôi muốn thay đổi thông báo lỗi cho tất cả các chế độ xem của mình. Vì vậy, hãy nói rằng tôi có quan điểm này có nghĩa là để đăng nhập người dùng, cung cấp email và mật khẩu. Nếu đúng, nó trả về access_token.
Nếu tôi đăng chỉ mật khẩu, nó sẽ trả về lỗi 400:
{"email": ["This field is required."]}
và nếu mật khẩu và email không phù hợp:
{"detail": ["Unable to log in with provided credentials."]}
những gì tôi muốn sẽ được nhiều hơn như:
{"errors": [{"field": "email", "message": "This field is required."}]}
{"errors": [{"non-field-error": "Unable to log in with provided credentials."}]}
Đây là của tôi xem:
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)
tôi có thể truy cập vào serializer.errors và thay đổi chúng, nhưng có vẻ như chỉ lỗi lĩnh vực có thể được truy cập theo cách đó, làm thế nào để thay đổi cũng lỗi xác nhận tạo ra trong serializer`s tôi xác nhận phương pháp?
Đây là tôi serializer (nó là serializer giống như rest_framework.authtoken.serializers.AuthTokenSerializer) nhưng thay đổi nội dung, vì vậy xác thực không đòi hỏi tên nhưng email:
class AuthTokenSerializer(serializers.Serializer):
email = serializers.CharField()
password = serializers.CharField()
def validate(self, attrs):
email = attrs.get('email')
password = attrs.get('password')
#print email
#print 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)
Hoặc có thể có một hoàn toàn khác nhau tiếp cận? Tôi sẽ thực sự cảm ơn vì bất kỳ ý tưởng nào.
Ou yeah, nó hoạt động !, Tôi không thể cảm ơn đủ Tom :) –
Bạn được chào đón! –
Để biết cách tiếp cận khác, hãy xem http://stackoverflow.com/questions/26943985/custom-error-messages-in-django-rest-framework-serializer – frnhr