7.6. Views Permissions
7.6.1. Class Based Views
https://docs.djangoproject.com/en/stable/topics/auth/default/#the-loginrequiredmixin-mixin
https://docs.djangoproject.com/en/stable/topics/auth/default/#the-permissionrequiredmixin-mixin
Login required:
>>>
... from django.contrib.auth.mixins import LoginRequiredMixin
...
...
... class MyView(LoginRequiredMixin, View):
... login_url = '/login/'
... redirect_field_name = 'redirect_to'
Permission Required:
>>>
... from django.contrib.auth.mixins import PermissionRequiredMixin
...
...
... class MyView(PermissionRequiredMixin, View):
... permission_required = ['customer.can_view', 'customer.can_edit']
User passes test:
>>>
... from django.contrib.auth.mixins import UserPassesTestMixin
...
...
... class MyView(UserPassesTestMixin, View):
... def test_func(self):
... return self.request.user.email.endswith("@example.com")
7.6.2. Function Based Views
https://docs.djangoproject.com/en/stable/topics/auth/default/#the-permission-required-decorator
https://docs.djangoproject.com/en/stable/topics/auth/default/#the-login-required-decorator
Login required:
>>>
... from django.contrib.auth.decorators import login_required
...
...
... @login_required
... def my_view(request):
... ...
Permission Required:
>>>
... from django.contrib.auth.decorators import permission_required
...
...
... @permission_required(['customer.can_view', 'customer.can_edit'])
... def my_view(request):
... ...
User passes test:
>>>
... from django.contrib.auth.decorators import user_passes_test
...
...
... def email_check(user):
... return user.email.endswith("@example.com")
...
... @user_passes_test(email_check)
... def my_view(request):
... ...