在 Django 中将模块的登录视图与我自己的登录视图集成

Integrating a module's login view with my own login view in Django

我正在尝试使用 this library to add two factor authentication to my project. I noticed that the module's has its own login view, that you can find right here,请参阅 class LoginView(IdempotentSessionWizardView):

我遇到的问题是我已经有自己的登录视图来处理身份验证表单,那么我为什么要使用模块的视图?我只需要将 2FA 部分添加到我自己的视图中,而不是使用另一个,但不幸的是,该模块在这部分并不是很清楚。

所以问题是:如何将他们的登录视图集成到我自己的登录视图中?如何在不使用其他登录处理程序的情况下将 2fa 部分添加到我自己的部分?

欢迎任何建议,这是我现有的登录视图:

def login_request(request):


    if request.method == "POST":

        if result['success']:
            form = AuthenticationForm(request, data=request.POST)
            if form.is_valid():
                username = form.cleaned_data.get('username')
                password = form.cleaned_data.get('password')
                user = authenticate(username=username, password=password)


                if user is not None:
                    login(request, user)
                    messages.info(request, f"You are now logged in as {username}")
                    return redirect("main:homepage")
                else:
                    messages.error(request, "Invalid username or password")

            else:
                messages.error(request, "Invalid username or password")

编辑:有人建议我使用自己的登录视图。是的,这会更容易。但将来我想在登录中添加更多内容,例如验证码表单或其他字段。但那是不可能的,因为我不会使用我自己的视图,而是使用模块的视图。是吗?

从此处的评论转换讨论:

一般来说,您希望在滚动自己之前使用 Django 提供的电池提供的视图,甚至在从头开始滚动您自己的视图之前,您希望继承和扩展 Django 视图,例如 LoginView.

同样的原则适用于(架构良好的)外部库,例如链接 django-two-factor-auth

首先,您只需使用其中包含的视图,可能是直接 include()ing urls module

然后,如果您确实需要在这些视图中自定义某些内容,您将从该视图继承,例如

from two_factor.views import LoginView

class MyLoginView(LoginView):
    template_name = 'super_fancy_login_template.html'
    form_list = (
        ('auth', MyAwesomeAuthenticationForm),
        # ... the rest from the original here ...
    )

并在 urls 之前 库提供的相同路径上的视图之前:

from django.conf.urls import url
from my_awesome_app.views import MyLoginView

urlpatterns = [
    url(
        regex=r'^account/login/$',
        view=MyLoginView.as_view(),
        name='login',
    ),
    include(...),
]

嘿,转眼之间,您已经用自己的视图替换了一个视图。

显然,您更换这样的零件越多,您拥有的东西就越少 "warranty"(开源软件根本不提供保修 ;))东西仍然可以正常工作。