DRF permissions - visitors can view but is_manager can POST, PUT, DELETE request

 permissions.py


from rest_framework.permissions import BasePermission

from rest_framework import permissions


class UnAuthenticatedOrReadOnly(BasePermission):

    def has_permission(self, request, view):

        if request.user.is_authenticated:

            if request.method in permissions.SAFE_METHODS:

                return True  # Allow unauthenticated users to perform GET and RETRIEVE

            return request.user.is_manager  # Only manager users can perform POST, PUT, DELETE

        return request.method in permissions.SAFE_METHODS  # Allow unauthenticated users to perform GET and RETRIEVE


    def has_object_permission(self, request, view, obj):

        if request.user.is_authenticated:

            return request.user.is_manager  # Only manager users can perform CRUD actions

        return request.method in permissions.SAFE_METHODS  # Unauthenticated users can only view

----------------------------------------------------------------------------------------------------------------------------------

views.py


from django.shortcuts import render

from rest_framework.viewsets import ModelViewSet

from core.models import Product

from .serializer import *

from .permissions import *

from rest_framework.permissions import IsAuthenticated, AllowAny

from rest_framework_simplejwt.authentication import JWTAuthentication



class ProductView(ModelViewSet):

    queryset = Product.objects.all()

    serializer_class = ProductSeralizer

    authentication_classes = [JWTAuthentication]

    permission_classes = [UnAuthenticatedOrReadOnly]

-----------------------------------------------------------------------------------------------------------------------------

serializers.py

        

from rest_framework import serializers

from core.models import Product


class ProductSeralizer(serializers.ModelSerializer):

    class Meta:

        model = Product

        fields = "__all__"

Popular posts from this blog

MCSL 216 MCA NEW Practical ~ common questions suggestions

dev chaeatsheet

STRAPI