Класс UserPassesTestMixin (Django 3.2)
from django.contrib.auth.mixins import UserPassesTestMixin
Deny a request with a permission error if the test_func() method returns False.
Предки (MRO)
- UserPassesTestMixin
- AccessMixin
Атрибуты
Определено в | |
---|---|
login_url = None
|
AccessMixin |
permission_denied_message = ''
|
AccessMixin |
raise_exception = False
|
AccessMixin |
redirect_field_name = 'next'
|
AccessMixin |
Методы
def dispatch(self, request, *args, **kwargs):
user_test_result = self.get_test_func()()
if not user_test_result:
return self.handle_no_permission()
return super().dispatch(request, *args, **kwargs)
Override this method to override the login_url attribute.
def get_login_url(self):
"""
Override this method to override the login_url attribute.
"""
login_url = self.login_url or settings.LOGIN_URL
if not login_url:
raise ImproperlyConfigured(
'{0} is missing the login_url attribute. Define {0}.login_url, settings.LOGIN_URL, or override '
'{0}.get_login_url().'.format(self.__class__.__name__)
)
return str(login_url)
Override this method to override the permission_denied_message attribute.
def get_permission_denied_message(self):
"""
Override this method to override the permission_denied_message attribute.
"""
return self.permission_denied_message
Override this method to override the redirect_field_name attribute.
def get_redirect_field_name(self):
"""
Override this method to override the redirect_field_name attribute.
"""
return self.redirect_field_name
Override this method to use a different test_func method.
def get_test_func(self):
"""
Override this method to use a different test_func method.
"""
return self.test_func
def handle_no_permission(self):
if self.raise_exception or self.request.user.is_authenticated:
raise PermissionDenied(self.get_permission_denied_message())
path = self.request.build_absolute_uri()
resolved_login_url = resolve_url(self.get_login_url())
# If the login url is the same scheme and net location then use the
# path as the "next" url.
login_scheme, login_netloc = urlparse(resolved_login_url)[:2]
current_scheme, current_netloc = urlparse(path)[:2]
if (
(not login_scheme or login_scheme == current_scheme) and
(not login_netloc or login_netloc == current_netloc)
):
path = self.request.get_full_path()
return redirect_to_login(
path,
resolved_login_url,
self.get_redirect_field_name(),
)
def test_func(self):
raise NotImplementedError(
'{} is missing the implementation of the test_func() method.'.format(self.__class__.__name__)
)