繁体   English   中英

'LoginForm' 对象没有属性 'get_user'

[英]'LoginForm' object has no attribute 'get_user'

我尝试使用基于登录类的视图登录,但是当我这样做时,它向我显示了这个错误:

AttributeError: 'LoginForm' 对象没有属性 'get_user'

这是我在 forms.py 中的登录表单代码:

from django import forms

class LoginForm(forms.Form):
    """
    The login form
    """
    def __init__(self, *args, **kwargs):
        self.request = kwargs.pop('request', None)
        super(LoginForm, self).__init__(*args, **kwargs)

    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

这是我在views.py中基于登录类的视图代码:

from django.contrib.auth.views import LoginView
from django.urls import reverse_lazy

from users.forms import LoginForm


class Login(LoginView):
    form_class = LoginForm
    template_name = 'users/login.html'
    success_url = reverse_lazy('phones:show')

我现在能做什么?

LoginView假设您使用django.contrib.auth.forms.AuthenticationForm作为具有get_user方法的表单。 查看您的实现,您不需要LoginForm类,因为AuthenticationForm已经完成了您的表单正在执行的操作,因此您的视图可以简单地为:

from django.contrib.auth.views import LoginView
from django.urls import reverse_lazy


class Login(LoginView):
    # Below line is not needed, let the parent class handle that
    # form_class = LoginForm
    template_name = 'users/login.html'
    success_url = reverse_lazy('phones:show')

事实上,如果我们真的仔细考虑这一点,您甚至不需要覆盖LoginView并且可以简单地将您需要的参数传递给as_view

path('login/', LoginView.as_view(template_name = 'users/login.html', success_url = reverse_lazy('phones:show')), name="login")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM