Django 'Loginform' object has no attributes get_user
i have multiuser type app with usertype and usertype b i am trying to create a loginform where most of of login is and should be in form am getting this error
forms.py
class Loginform(forms.Form):
username = forms.CharField(required=True)
password = forms.CharField(widget=forms.PasswordInput)
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
super().__init__(*args, **kwargs)
def clean(self):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
try:
user = models.User.objects.get(username=username)
if user.user_a:
if user.check_password(password):
return self.cleaned_data
else:
self.add_error("password", forms.ValidationError("Password is wrong."))
except models.User.DoesNotExist:
self.add_error("email", forms.ValidationError("User does not exist."))
views.py
class UseraView(LoginView):
template_name = 'login.html'
form_class = Loginform
success_url = reverse_lazy("home")
Note:There are some other stack post related to this which didn't help as those are for single type user here in my case it is multi user application so please dont provide any related links
LoginView
, when the form is valid, calls the form's get_user
method. This is because it is expecting the form class to be AuthenticationForm
or a subclass of it.
You can resolve this a few ways.
Override UseraView.form_valid
You could rewrite your view so that it doesn't call the form's method which you are missing. In this case you need some other way to authenticate the user in the view.
Subclass AuthenticationForm
Instead of inheriting from form.Form
you could inherit from Django's pre-existing authentication form. I don't think this would interfere with your clean
method, but it might be worthwhile looking at it again with the new tools provided by the new base.
Define Loginform.get_user
You could provide your own method which gets the user. You're already getting the user in Loginform.clean
so this wouldn't be difficult. I'd just look for a way to cache the user and not run the query twice.