经过身份验证后重定向自定义AuthenticationForm - Django

时间:2017-06-20 03:21:07

标签: django

一旦用户通过confirm_login_allowed的{​​{1}},是否可以重定向用户。

例如,我试图通过

重定向表单中的用户
AuthenticationForm

class LoginForm(AuthenticationForm): def confirm_login_allowed(self, user): if not user.is_active: raise forms.ValidationError('There was a problem with your login.', code='invalid_login') elif user.is_staff and not self.has_2fa(): logger.info('is staff but does not have 2FA, redirecting to Authy account creator') return redirect('admin/authy_me/authenticatormodel/') elif user.is_staff and self.has_2fa(): logger.info("is staff and 2FA enabled") elif not user.is_staff and not self.has_2fa(): logger.info('is not staff and does not have 2FA') 仅用于验证错误?如果有,还有其他办法吗?

1 个答案:

答案 0 :(得分:0)

得到了答案。 confirm_login_allowed无法进行任何重定向,您必须创建自定义视图,然后在那里进行重定向。

代表views.py

中的示例
def login(request):
    if request.user.is_staff and not has_2fa(request):
        logger.info('is staff but does not have 2FA, redirecting to Authy account creator')
        return redirect('admin/authy_me/authenticatormodel/')
    elif request.user.is_staff and has_2fa(request):
        logger.info("is staff and 2FA enabled")
    elif not request.user.is_staff and not has_2fa(request):
        logger.info('is not staff and does not have 2FA')

    defaults = {
        'authentication_form': LoginForm,
        'template_name': 'core/login.html',
    }

    return auth_login(request, **defaults)

并在urls.py中,而不是导入from django.contrib.auth.views import login导入from app_name.views import login,然后添加

url(r'^login/?$', app_name.login, name="login")
相关问题