1
votes

I developed an django app which register user and give resources based on resource level permissionIn this I am using django basic level permissions on my model and templates, there for view permission I set permission tuple in my model like:

class Model(AbstractUser):
    group = models.ForeignKey(AppGroup)
    class Meta:
        permissions = ( ('view_app', 'user can view app'), )

and I migrate my model after create my model like above.

Now for permissions, I created a group from admin and including all app view/change/delete permissions, using that group I generated a drop down in form class. Now user(admin) can create other users based on selected permissions and after register successfully the new user able to login successfully and access all resources but when I am trying to access user permissions which is a many-to-many relationship using like

class UserListView(ListView):
     def get_queryset(self):
         print(self.request.user.user_permissions.all())
         return super(UserListView, self).get_queryset()

When I list my view, it gives me a relation error (500 error): enter image description here relation views_list_user_permission does not exist

Now when I access the same view by superuser it gives me all permissions, but from a user which is neither superuser nor staff it spit out the above error. By reviewing djancgo.contrib.auth.models PermissionMixin class code it seems like to me the user_permissions m2m field can only access by superuser but I doubt it. So this is what I am doing and got the issue, please correct me if I take this in wrong way

1

1 Answers

1
votes

The superuser has all the set of permissions granted. Therefore you are able to see all the permissions. But when a new user is created he will not have any of the permissions set therefore there is no relation between the user and permissions so you are getting the above error.

Note:-

You can check for the available permissions for the logged in user inside template by using

{{ perms }}

For a specific app:-

{{ perms.app_name }}

For a specific model:-

{{ perms.app_name.model_name }}

Suppose you want to grant access to a user with specific permission to a particular model for a view you can use the permission required decorator like this:-

from django.contrib.auth.decorators import permission_required
@permission_required('polls.can_vote')
def my_view(request):
...

Now here the user with the permission can_vote on "polls" will be allowed the access grant.

For further detailed use you can refer:-

Django documentation on permissions.

The authentication back-end is responsible for user permissions. I guess you are using your own custom authentication back-end. However if you are doing so you may have forgot to import ModelBackend. from django.contrib.auth.backends import ModelBackend

Now make sure to extend this back-end into your own custom back-end

class EmailBackend(ModelBackend):