Custom permissions in Django
In Django Rest framework, we can verify permissions such as (isAuthenticated, isAdminUser...) but how can we add our custom permissions and decide what django can do with those permissions?
I really want to understand what happens behind (I didn't find a documentation that explaint this):
@permission_classes([IsAdminUser])
Thank you
If you are using VSCode, hover over @permission_classes([IsAdminUser])
, click on Command (on your keyboard).
You can see what happens behind the scenes, play and create your custom Django version (not recommended) or you can overwrite the function.
Write your own permissions, like this:
def permission_valid_token(func):
# first arg is the viewset, second is the request
def wrapper(*args, **kwargs):
valid_token, user_token = test_token_authorization(args[1].headers)
if not valid_token:
return Response(status=status.HTTP_401_UNAUTHORIZED)
return func(*args, **kwargs)
return wrapper
This a permission that i'm using in app, probably you will have the valid_token part
And them you import in your views
from file_that_you_use.permissions import permission_valid_token
And you use as a decorator
class WeatherViewSet(viewsets.ViewSet):
@permission_valid_token
def list(self, request):
This is just a viewset for example, you can use generic viewsets or whatever you want.