Ahmed Wagdi
Ahmed Wagdi

Reputation: 4371

how to change permissions for current view overriding the DEFAULT_PERMISSION_CLASSES in django rest-framework

how to change permissions for current view overriding the DEFAULT_PERMISSION_CLASSES in django rest-framework

Here is how i set my defaultpermissions in my settings.py :

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',  # <-- And here
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',
    ]
}

and i need to use AllowAny on the signUp method :

@permission_classes([AllowAny,])
@api_view(["POST", ])
def add_new_user(request):
    if request.method == "POST":
        lang = request.data["lang"]
..........
.........
.......

Still, it returns Authentication credentials were not provided. .. I mainly need to have permissions with a token with every request but not the register and login request. how to do it ??

Upvotes: 2

Views: 2318

Answers (2)

Carlos Carvalheira
Carlos Carvalheira

Reputation: 146

A Way to do that is using Object Level Permissions in Django. You just setup as normally in settings.py and add manually a permission into every class view. For me is the best way to do it. Normally will be Views witch is are Admin only, Authenticated or just Open.

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication', 
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoObjectPermissions',#Object Level Permission
        
    ]
}

After set this line into your settings.py just follow adding a permission_classes into view. Like:

class LoginUser(APIView):
    permission_classes = [AllowAny, ]
    ...

References

DjangoObjectPermissions

Django Class Based Views

Upvotes: 1

Ahmed Wagdi
Ahmed Wagdi

Reputation: 4371

Here is how I solved this :

in my settings.py i added both permissions classes

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework.authentication.TokenAuthentication',  # <-- And here
    ],
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated',  #both are mentioned 
        'rest_framework.permissions.AllowAny',
    ]
}

and in my view, I had to move the permission dictator to be the last thing before the view itself.

@api_view(["POST", ])
@permission_classes([AllowAny])
def login_user(request):
    if request.method == "POST":
        lang = request.data["lang"]
...

Upvotes: 1

Related Questions