'Are PermissionsMixin and PermissionRequiredMixin the same?
I want to know if PermissionsMixin
has the same function as PermissionRequiredMixin
.
from django.contrib.auth.models import PermissionMixin
from django.contrib.auth.mixins import PermissionRequiredMixin
Solution 1:[1]
No, PermissionsMixin
is a mixin for models, PermissionRequiredMixin
a mixin to mix in views.
I want to know if
PermissionsMixin
has the same function asPermissionRequiredMixin
.
These are not functions, but classes. The PermissionsMixin
is a mixin for models.
The PermissionsMixin
[Django-doc] is a mixin for Django models. If you add the mixin to one of your models, it will add fields that are specific for objects that have permissions, like is_superuser
, groups
, and user_permissions
. It also provides a set of utility methods to check if the model with this mixin has a given permission (for example with has_perm
[Django-doc]. A typical model that subclasses this mixin is the User
model [Django-doc].
The PermissionRequiredMixin
[Django-doc] mixin on the other hand is a mixin that provides a convenient way to check if the user that is logged in, has the required permission(s). For example:
from django.contrib.auth.mixins import PermissionRequiredMixin
class MyView(PermissionRequiredMixin, View): permission_required = ('polls.can_open', 'polls.can_edit')
Here we thus define a View
, but only users with these permissions, can access the view.
This mixin implements a get_permission_required()
method that generates an iterable of permissions to check, and a has_permission()
that checks if the user has these permissions. You can override these methods, for example if the permissions are dynamic (depend on the data in the database for example).
Solution 2:[2]
To make it easy to include Django’s permission framework into your own user class, Django provides PermissionsMixin. This is an abstract model you can include in the class hierarchy for your user model, giving you all the methods and database fields necessary to support Django’s permission model.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Andrés Sapatanga |