I'm writing a custom login functionality in the Django rest framework. But I can't check if the password is correct or not.
class LoginView(APIView):
def post(self, request):
username=request.data["username"]
password=request.data["password"]
user=User.objects.filter(username=username)
if user is None:
return Response({"response":"No User exist"})
if user.check_password(password):
return Response({"response":"correct Password"})
return Response({"data":"done"})
the problem is check_password function is not working.Is there any right way to do that or do I miss something in between?
CodePudding user response:
Check the documentation here https://docs.djangoproject.com/en/4.1/topics/auth/passwords/#django.contrib.auth.hashers.check_password
You need to compare the plain password in request.data["password"], with the password of the user in the DB.
from django.contrib.auth import authenticate
class LoginView(APIView):
def post(self, request):
username=request.data["username"]
password=request.data["password"]
user = authenticate(request, username=username, password=password)
if user is None:
return Response({"response":"No User exist"})
else:
return Response({"response":"correct Password"})
CodePudding user response:
Take a look at this one:
def login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
user = auth.authenticate(request, username=username, 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')
pass this in your template:
<div >
{% for message in messages %}
<h5>{{ message }}</h5>
{% endfor %}
<br>
</div>
CodePudding user response:
Fixed this issue by making an updation, I changed the filter() to get(), as filter() will return a query set but get () will return an object.
Updated Code :
class LoginView(APIView):
def post(self, request):
username=request.data["username"]
password=request.data["password"]
user=User.objects.get(username=username)
if user is None:
return Response({"response":"No User exist"})
if not user.check_password(password):
return Response({"response":"incorrect Password"})
return Response({"data":"done"})
If anyone still couldn't understand the difference of both functions (get and filter). Please check out the link Difference between Django's filter() and get() methods.
Thanks everyone who helps for the solution.