Django Login form issue - django

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

Related

prevent user to access login page in django when already logged in?

def admin_login(request):
if request.method == 'POST':
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request,username = username, password = password)
if user is not None:
if(user.is_superuser):
auth_login(request, user)
return redirect(reverse("dashboard"))
else:
messages.info(request, "invalid credentials")
return redirect(reverse("admin"))
return render(request,'login.html')
this is mylogin function for admin , how to prevent user to access login page once logged in?
You can check if the user who is requesting is authenticated and if so, you can redirect him to another page. You can check user if he is authenticated like this
if request.user.is_authenticated:
# redirect
so your view function will be like this
def admin_login(request):
if request.user.is_authenticated:
return redirect(reverse("admin"))
if request.method == 'POST':
username = request.POST["username"]
password = request.POST["password"]
user = authenticate(request,username = username, password = password)
if user is not None:
if(user.is_superuser):
auth_login(request, user)
return redirect(reverse("dashboard"))
else:
messages.info(request, "invalid credentials")
return redirect(reverse("admin"))
return render(request,'login.html')
do this in beginning of your login function
def user_login(request, *args, **kwargs):
if(request.user.is_authenticated):
print('user authenticated')
return HttpResponseRedirect('/')

Is Django AuthenticationForm authenticating with is_valid()?

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

Getting error 'django.contrib.auth.models.User.DoesNotExist: User matching query does not exist'

A similar question has been asked before but after going through all of them I was not able to find any answer to fit my case.
I am using Django's built-in authentication system to authenticate and log in a user. The user uses a log in form on index form and is supposed to be then redirected to a different url.
However after I log in with a username and password that are both valid entries, I am not redirected to the next url as I should be, and I get this error:
django.contrib.auth.models.User.DoesNotExist: User matching query does not exist.
These are my import lines for authenticate, login, and then for User.
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
But I don't think the problem is there.
It can't find the user but I don't know why that could be, because I am creating a username in the form and a password so it should be present.
Here is my login code:
def index(request):
if request.method == 'POST':
print("Received POST")
form = LoginForm(request.POST)
if form.is_valid():
print("FORM is Valid")
# proceed with registration
username, pwd = request.POST.get("username", None), request.POST.get("password", None)
if not username or not pwd:
print("nobody around here")
return HttpResponse("Username or password not present")
user = User.objects.get(username=username)
if user:
user = authenticate(username=username, password=pwd)
else:
user = User.objects.create_user(username, username, pwd)
login(request, user)
return redirect("dashboard")
else:
print("FORM is NOT VALID")
template = loader.get_template('index.html')
context = {
'username': 'Ralf',
'form': form,
}
return HttpResponse(template.render(context, request=request))
else:
# load the template file
template = loader.get_template('index.html')
context = {
'username': 'Ralf',
'form': LoginForm(),
}
return HttpResponse(template.render(context, request=request))
EDIT: I tried using a try except block and now the page will not load the form:
Here is the code I used:
if form.is_valid():
print("FORM is Valid")
# proceed with registration
username, pwd = request.POST.get("username", None), request.POST.get("password", None)
if not username or not pwd:
print("nobody around here")
return HttpResponse("Username or password not present")
try:
user = User.objects.get(username=username)
user = authenticate(username=username, password=pwd)
except:
user = User.objects.create_user(username, username, pwd)
login(request, user)
return redirect("dashboard")

login() is not working at all - Django

I have a django app and I am trying to integrate the login system that they have within the framework. I have the following line of code:
user = authenticate(username=username, password=password)
login(request, user)
I am running this method right after I create a new user after the user signs up and creates an account. I know the authentication is going to be successfull because I just created the account and I know it is there. I am gettting the following error
login() takes 1 positional argument but 2 were given
In the documentation is says you pass in a request and user... so why is it not working. this is driving me crazy....
Here is the documentation on djangos websites:
login(request, user, backend=None)[source]¶
To log a user in, from a view, use login(). It takes an HttpRequest object and a User object. login() saves the user’s ID in the session, using Django’s session framework.
Note that any data set during the anonymous session is retained in the session after a user logs in.
This example shows how you might use both authenticate() and login():
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
Here is my full signup method:
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
username = cd['username']
password = cd['password']
verify = cd['verify']
email = cd['email']
if password == verify:
secure_password = make_password(password)
user = User.objects.create(
username = username,
password = secure_password,
email = email,
)
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
else:
return redirect('home')
else:
form = SignupForm()
parameters = {
'form':form,
}
return render(request, 'users/signup.html', parameters)
else:
form = SignupForm()
parameters = {
'form':form
}
return render(request, 'users/signup.html', parameters)
if you havent declared any function with the same name as login
then
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
you missed the request in the authenticate.
and if you have declared a function with the name login then change it to something else

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'