5👍
Django authenticate
method allows for authenticating using only username.
You can get the user’s username from the User model using the user’s email
username = User.objects.get(email=email).username
password = request.POST.get('password')
Replace this user = authenticate(request, email=email, password=password)
with this user = authenticate(request, username=username, password=password)
3👍
The problem is django’s default authentication mechanism don’t allow you authenticate using email
, you can only authenticate user using username
.
either way, you can get the user’s username from the User model
using his email and then you can authenticate user.
def login(request):
if request.method == 'POST':
email = request.POST['email']
password = request.POST['password']
username = ''
try:
username = User.objects.get(email=email).username
except User.DoesNotExist:
return HttpResponse("Invalid")
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
print("Logged in")
else:
print("not logged in")
return redirect('/')
else:
return HttpResponse("Invalid")
Also dont store password directly, always user standard set_password()
function of django
if User.objects.filter(email=email).exists():
print("Email taken")
elif User.objects.filter(username=user_name).exists():
print("Username taken")
else:
user = User.objects.create_user(username = user_name, first_name=first_name,last_name=last_name, email=email)
user.set_password(pass1)
user.save()
print("User created")
0👍
The problem is your signup method. You should not give password
to the init function. You should use User’s set_password
method.
In your sign_up view remove password=pass1
at the line where you are creating User object. And after that before saving the user, add user.set_password(pass1)
.
Hope this helps!
- [Django]-Understanding / mySQL aka tricking ForeignKey relationships in Django
- [Django]-Improve django queryset performance
- [Django]-How to have nested url namespaces with a dynamic first part in Django
- [Django]-Display field other than __str__