'LoginForm' object has no attribute 'get_user'

Viewed 353

I tried to get login with login class based view, but when I did that, it Showed me this error:

AttributeError: 'LoginForm' object has no attribute 'get_user'

and this is my login form code in 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)

and this one is my login class based view code in 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')

what can I do now?

1 Answers

The LoginView works with the assumption that you are using django.contrib.auth.forms.AuthenticationForm as the form which has a get_user method. Looking at your implementation you don't need your LoginForm class as the AuthenticationForm already does what your form is doing, hence your view can simply be:

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

In fact if we really consider this carefully you don't even need to override LoginView and can simply pass the arguments you need in the call to as_view:

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