pythonmixinsdjango-2.0

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

  • No, PermissionsMixin is a mixin for models, PermissionRequiredMixin a mixin to mix in views.

    I want to know if PermissionsMixin has the same function as PermissionRequiredMixin.

    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).