Reputation: 15
I've created a user with my following code:
views.py (register view works fine but login view doesn't)
def register(request):
if request.method == 'POST':
form = UserProfileForm(request.POST)
if form.is_valid():
user = form.save()
username = ...
u = User.objects.create_user(username, user.email, user.password)
u.save()
...
else:
return HttpResponse('Nombre o contrasena incorrectos.')
else:
form = UserProfileForm()
...
def log_in(request):
if request.method == 'POST':
form = UserLoginForm(request.POST)
if form.is_valid():
email = form.cleaned_data['email']
password = form.cleaned_data['password']
try:
u = User.objects.get(email=email, password=password)
except User.DoesNotExist:
return HttpResponse('Email o contrasena incorrectos.')
...
else:
form = UserLoginForm()
...
The register view creates my custom user without any problem, but when I want to use it to login into my app, the login view throws a User.DoesNotExist
exception. Why is that?
Upvotes: 1
Views: 565
Reputation: 5611
The issue is here:
u = User.objects.get(email=email, password=password)
It has no sense, you can't compare password
field value, because it is not stored raw in database.
To check is user has provided correct password, you shoud use authenticate
built-in function:
u = authenticate(username=username, password=password)
You can see solid example here: http://code.runnable.com/UpBfbcg4PNU0AAHG/how-to-check-if-the-user-is-authenticated-in-django-for-python-authentication-and-httprequest
..or in official Django documentation (login
function example):
https://docs.djangoproject.com/en/1.8/topics/auth/default/#django.contrib.auth.login
Upvotes: 1