Want to send extra data from BasePermission to Queryset in ModelVIewSet DRF

78 views Asked by At

Here is My Seller Model which has User as OneToOneField

#models.py
.
. 
class CompanyProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user")
    company = models.CharField(max_length=255)
    pincode = models.IntegerField()
    city = models.ForeignKey(City, on_delete=models.CASCADE)
    address = models.TextField()
    profileActive = models.BooleanField(default=False)
.
.

Purchase Model

#models.py

class PurchaseOrder(models.Model):
    company = models.ForeignKey(CompanyProfile, on_delete=models.CASCADE)
    message = models.TextField(blank=True, null=True)
    expectedDelivery = models.DateField(blank=True, null=True)
    isCancel = models.BooleanField(default=False))
    updated_at = models.DateTimeField(auto_now=True)

#Custom permission_classes

class SellerCompanyActive(BasePermission):
    message = 'Only Seller with activated company account is allowed'
    def has_permission(self, request, view):
        user = AuthUser.objects.get(id=request.user.id)
        if user.is_seller:
            try:
                company = CompanyProfile.objects.get(user=user)
                if company.profileActive:
                    return True
                else:
                    self.message = "Company profile is not active"
            except CompanyProfile.DoesNotExist:
                self.message = "Company not found first create company"
        return False

In ModelViewSet

#views.py

class SellerPurchaseOrder(viewsets.ModelViewSet):
    queryset = PurchaseOrder.objects.all()
    serializer_class = PurchaseOrderSerializer
    authorization_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated, SellerCompanyActive]
    
    def get_queryset(self):
        user = self.request.user
        company = CompanyProfile.objects.get(user=user)
        return self.queryset.filter(company=company)

Now here I always had to use this

user = self.request.user
company = CompanyProfile.objects.get(user=user)

As their are lot of other views also, Is their any other way to send data from my custom permission_classes i.e from SellerCompanyActive to direct SellerPurchaseOrder->get_queryset

1

There are 1 answers

0
Varun On

You can set message attribute to be a dict, something like this:

class SellerCompanyActive(BasePermission):
    message = {'error': 'Only Seller with activated company account is allowed'}
    def has_permission(self, request, view):
        ...

you can add more fields to the dictionary to send more data