Django 2中的自定义LoginView

时间:2017-12-19 02:43:28

标签: django django-2.0

我正在尝试在Django 2中自定义身份验证和视图,但问题是如果用户已经过身份验证,则仍会显示登录表单,并且不会将其重定向到相应的URL。为了克服这个问题,我做了以下几点:

class CustomLoginView(LoginView):

    form_class = LoginForm
    template_name = 'login.html'

    def get_initial(self):
        if self.request.user.is_authenticated and self.request.user.is_staff and has_2fa(self.request.user):
            return HttpResponseRedirect(reverse('{}'.format(self.request.GET.get('next', 'portal_home'))))
        else:
            return self.initial.copy()

    def form_valid(self, form):

        if self.request.user.is_staff and not has_2fa(self.request.user):
            logger.info('is staff but does not have 2FA, redirecting to Authy account creator')
            auth_login(self.request, form.get_user())
            return redirect('2fa_register')
        auth_login(self.request, form.get_user())

        return HttpResponseRedirect(self.get_success_url())

HttpResponseRedirect中的get_initial()未重定向到/portal/页面。我还尝试了redirect('portal_home')但没有任何反应或者我是否需要编写自定义dispatch

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:3)

覆盖get()清除问题,请参阅https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-editing/#django.views.generic.edit.ProcessFormView

class CustomLoginView(LoginView):
    """
    Custom login view.
    """

    form_class = LoginForm
    template_name = 'login.html'

    def get(self, request, *args, **kwargs):
        if self.request.user.is_authenticated and self.request.user.is_staff and has_2fa(self.request):
            return redirect('{}'.format(self.request.GET.get('next', 'portal_home')))

        return super(CustomLoginView, self).get(request, *args, **kwargs)

    def form_valid(self, form):

        if self.request.user.is_staff and not has_2fa(self.request):
            logger.info('is staff but does not have 2FA, redirecting to Authy account creator')
            auth_login(self.request, form.get_user(), backend='django.contrib.auth.backends.ModelBackend')
            return redirect('2fa_register')

        return super(CustomLoginView, self).form_valid(form)

答案 1 :(得分:-1)

@Akshay我发现了一个干净实用的解决方案。 LoginView具有属性“ redirect_authenticated_user ”,只需设置URL名称/路径。