Python (Django) - Authenticate returning None - python

I'm using Django's authenticate function to let users register (create an account) and sign in (login after creating an account). Authenticate works fine for registration, but when I try signing the user in after logging out, it doesn't work.
Registration Method:
if request.method == 'POST':
form = SignUpForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
raw_password = form.cleaned_data['password1']
user = authenticate(username=username, password=raw_password) #returns user object
login(request, user) #works
Sign in Method:
if request.method == 'POST':
form = AuthenticationForm(request=request, data=request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user = authenticate(user=username, password=password) #returns None
login(request, user) #doesn't work
I looked at a few other threads that reported a similar issue and added the following code to my settings.py file. However, authenticate still returns none when I try signing in.
settings.py code
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
)

As per Django documentation for authenticate method, the valid keyword arguments are username and password. Thus, I would recommend changing the following in "Sign In" method:
user = authenticate(user=username, password=password)
to
user = authenticate(request=request, username=username, password=password)

Related

Django authenticate: usage in login vs. register (signup): how do they differ?

I have noticed that the Django authenticate is used in the same way in both the login view and the register view, both return a User object to be used in the login().
In the login view authenticate() uses username and password from the submitted form, then checks on user if the credentials are ok.
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password1']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
The register view looks very similar to the login view. It gets the credentials from the submitted form and uses the user to login.
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data['username']
password = form.cleaned_data['password1']
user = authenticate(request, username=username, password=password)
login(request, user)
Both call user = authenticate(request, username=username, password=password).
Apart from saving the form in the register view, what is the difference here? Because the login (I guess) is only checking that the credentials are valid, but the register is creating a new user and, since it is creating, the credentials are new data coming in. Am I getting this correctly?
You do not need to authenticate a user in your register method. It can be as simple as,
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
return redirect('<urlname>')
context = {'form': form}
return render(request, '<appname>/<filename>.html', context)
Hence, authentication is only required while logging in as a user. And you can make your login method even simpler by doing this,
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request, username=username, password=password)
if user:
login(request, user)
return redirect('<urlname>')
return render(request, '<appname>/<filename>.html')
Hope this clarifies the situation for you :)

How can I change django login form from username to email when users wanted to login

Is there anyways I can change django custom user login from Username to Email? I have try using this method but it does not work:
def login(request):
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
user = auth.authenticate(request, email=email, password=password)
if user is not None:
auth.login(request, user)
return redirect('Home')
else:
messages.info(request, 'Invalid Credential')
return redirect('login')
else:
return render(request, 'login.html')
I want to allow user to login using Email not Username.

Is there anyway to customise authenticate function of Django?

I am fairly new to Django so I wanted to know what should I do to make default authenticate function of Django accepts only email and password to login, assuming that in sign-up form I have both username and email. The following code does not work properly.However when I add
username = request.POST.get('username')
and change
user = authenticate(request, username=username email=email, password=password)
It logs in as expected.
The login View:
def LoginPage(request):
if request.method == 'POST':
email = request.POST.get('email')
password = request.POST.get('password')
user = authenticate(request, email=email, password=password)
if user is not None:
login(request, user)
print('logged')
return redirect('/inker/')
return render(request, 'authy/login.html')
The sign up view:
def SignUpPage(request):
form = CreateUserForm()
if request.method == 'POST':
form = CreateUserForm(request.POST)
if form.is_valid():
form.save()
return redirect('/login/')
context={'form':form}
return render(request, 'authy/signup.html', context)
The form module:
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username','email', 'password1', 'password2']
As you can see in Sign Up view we have both username and email but in login form I want it to just login user based on only email. How can I implement this.
Also how can I compact both username and email into one input when user wants to login? pretty much like instagram, facebook login page
If you just want to access user using email, you're not using authentication on the first place. So, to solve your purpose, following approaches can be followed:
Get user email in url params in every request (so that user can be identified)
Set default password while creating the user account for all users and use that password while authentication (not recommended)

Django Get None After User Authentication

def login_page(request):
form = LoginForm(request.POST or None)
context = {
"form" : form
}
print("User logged in")
print(request.user.is_authenticated())
if form.is_valid():
print(form.cleaned_data)
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(request, username = 'username', password = 'password')
print(user)
if user is not None:
print(request.user.is_authenticated())
login(request, user)
# Recirect to a success page.
# context['form'] = LoginForm()
return redirect("/contact")
else:
# Return an 'invalid login' error message.
print("Error")
return render(request, "auth/login.html", context)
I try to create a login page but I get value of 'user' None so I took error everytime. I use Django 1.11.
You are trying to authenticate with constant credentials but need to authenticate with data from form.
username = form.cleaned_data.get('username')
password = form.cleaned_data.get('password')
user = authenticate(request, username=username, password=password)
# ^ ^
# changed from 'username' and 'password' to variables
If your user provided wrong credentials, then authenticate return None, since no user can be authenticated with those.

PASSWORD_HASHERS setting in Django

i have an error when ever i try to login by any User
error
Unknown password hashing algorithm 'sahar'. Did you specify it in the
PASSWORD_HASHERS setting?
Views.Py
def Login(request):
state = "Please log in below..."
username = password = ''
if request.method == 'POST':
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)
return HttpResponseRedirect('/profile/')
else:
return render_to_response('auth.html',RequestContext(request))
else:
return render_to_response('auth.html',RequestContext(request))
else:
return render_to_response('auth.html',RequestContext(request)
It means there is a plain text 'sahar' stored as the password of the account of a user who tries to log in.
Update the password of the user in Admin or in manage.py shell
user = User.objects.get(username=username)
# use set_password method
user.set_password('sahar')
user.save()
# INSTEAD OF
user.password = 'sahar'
user.save()
Also check your other views to correct the user.password = '...' and User.objects.create(password='...') usages.
This is the best way to save log in details
you can create an object from the form
as
user = form.save(commit=False)
then clean the data to remove any scripts entered in the form fields.
username = form.cleaned_data['username']
password = form.cleaned_data['password']
user.set_password(password)
user.save()

Categories

Resources