0

I have a Car model in my car_store app.

class Car(models.Model):
    ...
    class Meta:
        permissions = (('can_buy', 'User can buy this car'),)

Right now I have a custom User model in my accounts app which is:

from django.db import models as _models
from django.contrib.auth.models import AbstractBaseUser

class User(AbstractBaseUser):
    email = models.EmailField()
    ....
    def has_perms(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True        

and later I would simple make use of PermissionRequiredMixin for my view:

from django.contrib.auth.mixins import PermissionRequiredMixin
from django.views.generic import ListView

class CarListView(PermissionRequiredMixin, ListView):
    permission_required = ('car.can_buy',) 

The question is django does not offer any type of self.set_perm(self, perm) or set_perm(some_user, perm)? If not, what would be the simplest way to implement it?

Should I simply do something like this?

class User(AbstractBaseUser):
    perms = []
    def set_perm(self, perm):
        self.perms.append(perm)
    def has_perm(self, perm):
        return self.perms.count(perm)

I couldn't find nothing that describes how to set a perm to an user (except third-party django-guardian - assign_perm()). Neither a Full Example from django docs talks about how to set a perm to the User. There's even this Answer, but he doesn't talk about setting the perm to the user, but just how to check for a perm.

R.R.C.
  • 5,439
  • 3
  • 14
  • 19
  • Is there any specific reason that you don't use `BooleanField` like `is_staff` or sth else? – seuling May 15 '18 at 06:31
  • Also, there's `groups` in django. You can add/minus authentication for each groups. check [here](https://docs.djangoproject.com/en/2.0/topics/auth/) – seuling May 15 '18 at 06:32
  • @seuling, Yes, there's a reason. A project I'm woking on should have two type of users, a Master and an Analyst. The analyst can't access all the urls. Being staff in this case, the analysts would have much power, which they should not. – R.R.C. May 15 '18 at 06:36
  • Ok. then I think you can use custom backend. I will upload answer – seuling May 15 '18 at 06:43

0 Answers0