Is Django AuthenticationForm authenticating with is_valid()? - django

When I use AuthenticationForm in my login view, I find that when I check form.is_valid(), it returns False if the user creds are incorrect. I thought that is_valid() checks validity based on the form class's validation criteria and not by actually doing a database query. Am I incorrect?
For examples here's a simple login view:
def login_form(request):
if request.method == 'POST':
form = AuthenticationForm(request, data=request.POST)
if form.is_valid():
email = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(request, username=email, password=password)
if user is not None:
login(request, user)
messages.info(request, f"Welcome back {request.user.first_name}.")
return redirect('home')
else:
messages.error(request, "Why is this not returned for invalid creds?")
else:
messages.error(request, "This is returned for invalid creds.")
else:
form = AuthenticationForm()
return render(request, 'login.html', {'form': form})
form.is_valid() returns False if I enter a proper email and password for a non-existent account. I would think that it would return True, and user would be None when we authenticate().
Is is_valid() authenticating the user credentials? Please provide a reference.

Yes, it does try to authenticate. Here is what it tests:
def clean(self):
username = self.cleaned_data.get('username')
password = self.cleaned_data.get('password')
if username and password:
self.user_cache = authenticate(username=username,
password=password)
if self.user_cache is None:
raise forms.ValidationError(
self.error_messages['invalid_login'],
code='invalid_login',
params={'username': self.username_field.verbose_name},
)
else:
self.confirm_login_allowed(self.user_cache)
return self.cleaned_data

Related

How can i ensure that users can be logged in and after logging out, they can still log in again

def LoginForm(request):
Form= 'Login'
if request.user.is_authenticated:
return redirect('home')
if request.method == "POST":
username = request.POST.get('username')
password = request.POST.get('password')
# to see if the user exist within the db
try:
user = User.objects.get(username=username)
except:
messages.error(request, 'User does not exist')
# if the user exist, we will use the auth method, import it
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
messages.error(request, 'Username or password does not exist')
context = {'Form': Form}
return render(request, 'base/registration_log.html', context)
The above code is the user log in function. but once they log in and log out, they are not able to log in again

Django Login form issue

Views.py
def Tourist_login(request):
if request.method == 'POST':
form = Tourist_login_form(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username,password=password)
print(user)
if user is not None:
login(request,user)
messages.success(request,'logged in')
return redirect('home')
else:
messages.error(request,"Invalid login credentials!")
return redirect('touristlogin')
else:
return redirect('touirstlogin')
else:
form = Tourist_login_form()
return render(request,'accounts/tourist_login.html',{'form':form})
In the above code , authenticate function returns none value. But if I'm passing input in form through superuser credentials then it is working fine. I'm not able why is it not taking the username and password passed by the user and only taking superuser username and password.
Please try using this way:
from django.contrib.auth.models import auth
user = auth.authenticate(username=username, password=password)
if user is not None:
auth.login(request, user)
messages.success(request,'logged in')
return redirect('home')

Why django form valdation error does not work in my form

I want to show user validation error but seems that this is not working in my login form here is the code
my forms.py
class LoginForm(forms.Form):
username = forms.CharField(widget=forms.TextInput())
password = forms.CharField(widget=forms.PasswordInput())
remember_me = forms.BooleanField(required=False, label='Remember Me',help_text='Keep me logged in.',widget=forms.CheckboxInput())
def clean(self, *args, **kwargs):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
if username and password:
user = authenticate(username=username, password=password)
if not user:
raise forms.ValidationError("This user doesn't exist")
if not user.check_password(password):
raise forms.ValidationError("Incorrect Password")
if not user.is_active:
raise forms.ValidationError("User no longer Active")
return super(LoginForm,self).clean(*args,**kwargs)
my views.py for login
def my_login(request):
if 'next' in request.GET:
messages.add_message(request, messages.WARNING, 'To Continue, Please login here!')
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
remember_me = form.cleaned_data['remember_me']
user = authenticate(username=username, password=password)
if user:
login(request, user)
if not remember_me:
request.session.set_expiry(0)
return redirect('accounts:home')
else:
request.session.set_expiry(1209600)
return redirect('accounts:home')
else:
messages.info(request, 'Please check your credentials.')
return redirect('accounts:login')
else:
form = LoginForm()
return render(request, "login.html", {'form': form})
i know i am redirecting the form if form credential is wrong but if i don't i will throw error didn't return a httpresponse it return none instead also want to what is the best way to redirect or show exact validation error of which credential is wrong

want to remove error message in custom login form in django custom login

i don't want user have to see this message without any error i load page this come automatically here is my views.py
def my_login(request):
form = LoginForm(request.POST)
if form.is_valid():
username = form.cleaned_data["username"]
password = form.cleaned_data["password"]
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
return redirect('accounts:home')
else:
return HttpResponse('<h1>Page was found</h1>')
else:
return render(request, "login.html", {'form': form})
my forms.py
class LoginForm(forms.Form):
username = forms.CharField()
password = forms.CharField(widget=forms.PasswordInput)
def clean(self, *args, **kwargs):
username = self.cleaned_data.get("username")
password = self.cleaned_data.get("password")
if username and password:
user = authenticate(username=username, password=password)
if not user:
raise forms.ValidationError("User does not exist.")
if not user.is_active:
raise forms.ValidationError("User is no longer active.")
return super(LoginForm, self).clean(*args, **kwargs)
You need to submit your form only when you receive a POST request.
def my_login(request):
if request.method == 'POST':
form = LoginForm(request.POST)
if form.is_valid():
# process form here
else:
form = LoginForm()
# send form to template
You will find more info about this in the documentation.

django.contrib.auth.views.login returns Anonymous user

I want to login my user after registration, but when call login(request, user) then request.user is still AnonymousUser.
def register(request):
if request.method=='POST':
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
pwd = form.cleaned_data['password1']
user = authenticate(username=username, password=pwd)
if user is not None and user.is_active:
auth_views.login(request, user)
return redirect('/')
else:
form = RegistrationForm()
return render(request, 'registration.html', {'form' : form})
When calling login in my own login method, it works correct. But in
`register` view not:
def login(request):
if request.method=="POST":
form = AuthenticationForm(data=request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(username=username, password=password)
if user is not None and user.is_active:
auth_views.login(request, user)
return redirect(reverse('chat'))
else:
return redirect('/')
else:
form = AuthenticationForm()
return render(request, 'login.html', {'form':form})
Try:
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
# Redirect to a success page.
else:
# Return a 'disabled account' error message
...
else:
# Return an 'invalid login' error message.
...
And check your session settings
Did you remember to define the Auth user in your settings file? If not, you should add the following line to your settings.py:
AUTH_USER_MODEL = 'your_app.your_usermodel'