Django REST Framework has an excellent piece of documentation about permissions. I've been able to use pre-made permission classes and also built my own.
However, there are some API methods in which a "Permission denied" generic message is not very informative for the user. For example, if the user is authenticated but the account has expired, it would be nice to let the user know that his account is expired and not just a permission denied error.
When building custom permission classes, you either return True
or False
- according to the documentation. But I would like, as said above, to show a more informative message to the user. How to accomplish this?
Since DRF 3.2.0, You only have to add a message attribute :
See from DRF documentation: http://www.django-rest-framework.org/api-guide/permissions/#custom-permissions
By default, it is handled by default exception handler, and it is raising a standard message - https://github.com/tomchristie/django-rest-framework/blob/2eb9107b875972e442ed73eef0e653fd4480d873/rest_framework/views.py#L82
But, you can set own
EXCEPTION_HANDLER
in settings of DRF, and handlePermissionDenied
exception to return message you want.See description at http://www.django-rest-framework.org/api-guide/settings/
From DRF
you can simply add
message
attribute.It will return a
dict
with keydetail
, something like this:We can
set message attribute
not tostring
but todict
, something like this:In this case the error will be:
I faced the same problem using DRF 3.9.4. As a workaround I defined just a simple message property in the custom permission class and it works. You can also use getattr with the same result I guess.