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
Related
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')
I collect two forms at signup - a register form and a user profile form.
The form submission works alright - I get to see the new user and their profile on the admin panel. The problem would be automatically logging them in and redirecting them to a specific page doesn't seem to work.
This is what my views.py file look like:
def registerView(request):
regForm = RegisterForm
proForm = UserProfileForm
if request.method == 'POST':
regForm = RegisterForm(request.POST)
proForm = UserProfileForm(request.POST)
if regForm.is_valid() and proForm.is_valid():
user = regForm.save(commit=True)
profile = proForm.save(commit=False)
profile.user = user
profile.save()
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request, user)
return render (request, 'main/dashboard.html', {})
else:
return HttpResponse("There was a problem signing you up!")
regDic = {'regForm': regForm, 'proForm': proForm}
return render(request, 'person/register.html', context=regDic)
What would be the best way to automatically log in & redirect the registered user upon form submission?
Try using redirect instead of render.
from django.shortcuts import redirect
if user:
if user.is_active:
login(request, user)
return redirect('name of the url you want to redirect')
First use the cleaned_data from the valid form instead of getting the raw values and then instead of render the template redirect to some path after the successful login.
And also the authenticate function should have request as the first parameter.
username = regForm.cleaned_data.get('username')
password = regForm.cleaned_data.get('password')
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('some_path')
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")
I am athenticating user and redirecting him to index page:
def sign_user(request):
username = request.POST['login']
password = request.POST['pwd']
user = authenticate(username=username, password=password)
if user is not None:
print('success:' + username + " " + password)
return redirect('/')
this is index view:
def index(request):
user = request.user
print(user)
And as a result here I get: AnonymousUser
What do I do?
You need to login the user, like the docs say.
if user is not None:
login(request, user)
Try this way,
from django.contrib.auth import authenticate, login
def sign_user(request):
username = request.POST['login']
password = request.POST['pwd']
try:
user = authenticate(username=username, password=password)
login(request, user)
return redirect('/') # login success
except:
return redirect('unable to login')
I am making a login form in django. When I am running the app and filled the username and password fields. The page always redirected to one condition (whether the username is right or not).
The code is as :
def home(request):
if request.method == 'POST':
username = request.POST.get('user_name')
password = request.POST.get('password')
user = authenticate(user_name=username, password=password)
if user is not None:
if user.is_active:
login(request, user)
# success
return render_to_response('registration/main_page.html',{'form':login},context_instance=RequestContext(request))
else:
#user was not active
return render_to_response('registration/q.html')
else:
# not a valid user
return render_to_response('registration/home.html')
else:
# URL was accessed directly
return render_to_response('registration/w.html')
It always redirected to home.html
else:
#user was not active
return render_to_response('registration/home.html')
Why it happens?
authenticate() function takes username not user_name.
Try this: user = authenticate(username=username, password=password)
Also, instead of if user is not None: you can write if user :
It seems your function returns a None object here:
if user is not None
You can add print statements to pin it down,
if request.method == 'POST':
username = request.POST.get('user_name')
password = request.POST.get('password')
print username # what does it return?
user = authenticate(user_name=username, password=password)
print user # what does it return?
if user is not None:
#...