Home > Software design >  Django Rest Framework: generics.RetrieveUpdateDestroyAPIView not working for the given below conditi
Django Rest Framework: generics.RetrieveUpdateDestroyAPIView not working for the given below conditi

Time:06-22

In this generic APIView when I'm trying to log in through a non-admin user it is giving "detail": "You do not have permission to perform this action." but working fine for the admin user.

I don't whether the problem is in code or permission.py
I've shared my Views.py, permissions.py, and models.py for the same.
If there is any mistake in my def get_queryset(self): please do let me know.

Thank you!!

class BookingRetrtieveUpdateDestroyAPIView(generics.RetrieveUpdateDestroyAPIView):
    permission_classes = [IsUserOrIsAdmin]
    # queryset = Booking.objects.all()
    # serializer_class = BookingSerializer
    def get_queryset(self):

        if self.request.user.is_admin == False:

            user_data= self.request.user
            book = Booking.objects.filter(user= user_data)
            return book
        else:
            book = Booking.objects.all()
            return book

    serializer_class = BookingSerializer
permissions.py


from django.contrib.auth import get_user_model
from rest_framework.permissions import BasePermission

User = get_user_model()


class IsUserOrIsAdmin(BasePermission):
    """Allow access to the respective User object and to admin users."""

    def has_object_permission(self, request, view, obj):
        return (request.user and request.user.is_staff) or (
            isinstance(obj, User) and request.user == obj
        )
views.py

class User(AbstractBaseUser):
    email = models.EmailField(verbose_name='Email',max_length=255,unique=True)
    name = models.CharField(max_length=200)
    contact_number= models.IntegerField()
    gender = models.IntegerField(choices=GENDER_CHOICES)
    address= models.CharField(max_length=100)
    state=models.CharField(max_length=100)
    city=models.CharField(max_length=100)
    country=models.CharField(max_length=100)
    pincode= models.IntegerField()
    dob = models.DateField(null= True)


    # is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name','contact_number','gender','address','state','city','country','pincode','dob']

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        "Does the user have a specific permission?"
        # Simplest possible answer: Yes, always
        return self.is_admin

    def has_module_perms(self, app_label):
        "Does the user have permissions to view the app `app_label`?"
        # Simplest possible answer: Yes, always
        return True

    @property
    def is_staff(self):
        "Is the user a member of staff?"
        # Simplest possible answer: All admins are staff
        return self.is_admin


class Booking(models.Model):
    user =models.ForeignKey(User,on_delete=models.CASCADE)
    flights =models.ForeignKey(Flight,on_delete=models.CASCADE)
    passenger =models.ManyToManyField(Passenger)
    booking_number= models.CharField(max_length= 100,default=0, blank= True)
    booking_time = models.DateTimeField(auto_now_add=True)
    no_of_passengers= models.IntegerField(default=0,blank= True)

    def __str__(self):
        return self.booking_number

CodePudding user response:

Assuming that you want to allow non-admin users to access their bookings the permission class would have to look like:


class IsUserOrIsAdmin(BasePermission):

    def has_object_permission(self, request, view, obj):
        return (
           # staff can do everything
           (request.user and request.user.is_staff) or 
           # accessed obj is a Booking and belongs to the user
           (isinstance(obj, Booking) and request.user.pk == obj.user.pk) or 
           # user can access or modify his user object
           (isinstance(obj, User) and request.user.pk == obj.pk)
        )
  • Related