4
  • When I don't pass the header in postman, DRF gives me this message.

     {"detail": "Authentication credentials were not provided."}
    
  • But I want a custom message like the following.

       {
           "status": False,
           "message": "Authentication credentials were not provided.",
           "data": {}
       }
    
niamulbengali
  • 292
  • 1
  • 3
  • 16
kartik
  • 43
  • 3
  • 2
    Does this answer your question? [Django rest\_framework custom error message](https://stackoverflow.com/questions/51665260/django-rest-framework-custom-error-message) – JPG Dec 02 '20 at 05:48

1 Answers1

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': {}
                 }
Ohad the Lad
  • 1,889
  • 1
  • 15
  • 24