Есть ли способ расширить декоратор Django login_required для проверки наличия поля boolean в моей пользовательской модели?
Я работаю над веб-приложением, которое имеет 5 различных типов пользователей, которые различаются с помощью булевых полей в моей пользовательской модели пользователя.
is_estate_vendor = models.BooleanField(
_('estate_vendor'),
null=True,
blank=True,
help_text=_(
'Designates whether this user should be treated as an estate admin.'
),
)
is_estate_admin = models.BooleanField(
_('estate_admin'),
null=True,
blank=True,
help_text=_(
'Designates whether this user should be treated as an estate admin.'
),
)
is_estate_security = models.BooleanField(
_('estate_security'),
null=True,
blank=True,
help_text=_(
'Designates whether this user should be treated as estate security.'
),
)
is_estate_residence = models.BooleanField(
_('estate_residence'),
null=True,
blank=True,
help_text=_('Designates whether this user should be treated as estate residence.'
),
)
is_estate_head_security = models.BooleanField(
_('estate_head_security'),
null=True,
blank=True,
help_text=_(
'Designates whether this user should be treated as estate head security.'
),
)
is_super_admin = models.BooleanField(
_('super_admin'),
null=True,
blank=True,
help_text=_(
'Designates whether this user should be treated as superadmin.'
),
)
Я пытаюсь расширить Django login_decorator для проверки того, какой пользователь вошел в систему, на основе того, какое из этих булевых полей истинно, и перенаправить любого аутентифицированного пользователя на страницу входа, если он/она пытается получить доступ к приборной панели пользователя другого типа. Я попытался создать пользовательский декоратор, который проверяет эти поля:
def vendor_login_required(function):
def wrapper(request, *args, **kwargs):
vendor=request.user.is_estate_vendor
userAuth = request.user.isAuthenticated:
if not userAuth:
message.success(request, "Please login")
return HttpResponseRedirect('/login')
elif userAuth and not vendor:
message.error(request, "You are not authorized to be here, login as a vendor to
continue")
return HttpResponseRedirect('/login')
else:
return function(request, *args, **kwargs)
return wrapper
По какой-то причине это не работает, я буду признателен за способ обойти это.
Ваш пример более применим к декоратору @user_passes_test, где вам просто нужно вернуть True или False, должно ли представление быть продолжено или должно быть перенаправлено на страницу входа, больше не нужно вручную выполнять HttpResponseRedirect или вызывать view.
user_passes_test(test_func, login_url=None, redirect_field_name='next')В качестве сокращения можно использовать удобный декоратор user_passes_test, который выполняет перенаправление, когда вызываемый элемент возвращает False:
Это будет выглядеть примерно так:
from django.contrib.auth.decorators import login_required, user_passes_test
def is_estate_vendor(user):
return user.is_estate_vendor
@login_required # This will check if a user is currently logged-in, whether estate vendor, admin, security, etc.
@user_passes_test(lambda user: user.is_estate_vendor) # This will check of the user has the correct boolean fields set to access this view
# @user_passes_test(is_estate_vendor) # Use this if you need to use the function above to perform more complex checks
def my_view_for_estate_vendor(request):
...