Django 2中的自定义LoginView [英] Custom LoginView in Django 2

查看:200
本文介绍了Django 2中的自定义LoginView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试自定义身份验证并在Django 2中查看,但问题是,如果用户已经通过身份验证,则仍显示登录表单,并且该表单不会重定向到适当的URL。为了克服这个问题,我做了以下工作:

I am trying to customise the authentication and view in Django 2 but the problem is that if the user is already authenticated the login form is still shown and it is not redirected to the appropriate URL. To get over this I have done the following:

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())

但是 get_initial()中的 HttpResponseRedirect 不会重定向到 / portal / 页。我也尝试过 redirect('portal_home'),但是什么也没有发生,还是我需要编写自定义的 dispatch

But the HttpResponseRedirect in get_initial() does not redirect to the /portal/ page. I have also tried redirect('portal_home') but nothing happens or do I need to write a custom dispatch?

任何帮助将不胜感激。

推荐答案

覆盖 get()可以解决问题,请参见 https://docs.djangoproject.com/en/dev/ref/class-based-views/mixins-editing/#django.views.generic.edit .ProcessFormView

Overriding get() clears the problem see 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)

这篇关于Django 2中的自定义LoginView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆