[Django]-How to customize [Authentication credentials were not provided] error message in Django rest framework

0👍

For all requests or just for one or two API endpoints ?

If it is for some api’s do as Arakkal Abu linked you in comments.
I find MyCustomExcpetion answer to be nice.

If it is for all endpoints use a serializer / middleware like this (JWT EXAMPLE):

file: url.py
from rest_framework_jwt.views import ObtainJSONWebToken, refresh_jwt_token

url('auth/', ObtainJSONWebToken.as_view(
    serializer_class=CustomJWTSerializer)),


file: serializer.py

from rest_framework import serializers
from rest_framework_jwt.serializers import JSONWebTokenSerializer
from rest_framework_jwt.utils import jwt_encode_handler, jwt_payload_handler

class CustomJWTSerializer(JSONWebTokenSerializer):
    
    def validate(self, attrs):
        credentials = {
                'email': attrs.get('email'),
                'password': attrs.get('password')
            }
        if all(credentials.values()):
            user = authenticate(**credentials)
            if user:
                payload = jwt_payload_handler(user)
                return {
                   'token': jwt_encode_handler(payload),
                   'user': user}
            else:
                return {msg: 'other error msg'}
        else:
            return {
             'status': False,
             'message': 'Authentication credentials were not provided.',
             'data': {}
                 }

Leave a comment