Python Django, How I Can use username(uname) or email as a login credentials ? my python file are views,URLs,models,settings.py
def loginpage(request):
if request.method=="POST":
try:
Userdetails=newacc.objects.get(email=request.POST['email'],pwd=request.POST['pwd'])
print("Username=",Userdetails)
request.session[ 'email']=Userdetails.email
return render(request,'Logout.html')
except newacc.DoseNotExist as e:
messages.success(request,' Username / Password Invalid.')
return render(request,'Login.html')
CodePudding user response:
You can work with a Q object to make a disjunction between email and uname:
from django.db.models import Q
if request.method=="POST":
try:
Userdetails=newacc.objects.get(
Q(email=request.POST['email']) | Q(uname=request.POST['email']),
pwd=request.POST['pwd']
)
print("Username=",Userdetails)
request.session[ 'email']=Userdetails.email
return render(request,'Logout.html')
except newacc.DoseNotExist as e:
messages.success(request,' Username / Password Invalid.')
return render(request,'Login.html')
But it seems that your user model does not make use of password hashing. I strongly advise to read the documentation on password management and hash passwords in your user model to prevent hackers from exploiting the passwords stored in the database if they manage to read that. See also this section on Customizing Authentication in Django.
