I am working on a vehicle project management system, and using a custom table for storing the signup details in MySQL. When the user logins the authenticate function returns none always, I am using email and password fields for login
- checked the values are retrieving from database correctly or not
- The backend authentication
Here is userProfile model
class UserProfiles(models.Model):
full_name=models.CharField(max_length=200)
phone_number=models.IntegerField()
email=models.CharField(unique=True,max_length=20)
password=models.CharField(max_length=200)
# is_active = models.BooleanField(default=True)
# is_staff = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['full_name', 'phone_number']
def set_password(self, password):
self.password = make_password(password)
def check_password(self, password):
return check_password(password, self.password)
‘
def userLogin(request):
if request.method == 'POST':
email = request.POST.get('email')
password = request.POST.get('password')
print('from loginhtml page',email,password)
try:
user_profile = UserProfiles.objects.get(email=email)
user = authenticate(request, username=email, password=password)
print("from database ",user_profile.email,user_profile.password)
print(user)
if user is not None:
login(request, user)
messages.success(request, 'You have been logged in successfully.')
return redirect('/DashboardPage.html')
else:
error_message='Invalid email or password. Please try again.'
messages.error(request, error_message)
except UserProfiles.DoesNotExist:
error_message='Invalid email or password. Please try again.'
messages.error(request, error_message)
return render(request, 'userLogin.html')
from django.contrib.auth.backends import BaseBackend
from django.contrib.auth import get_user_model
from django.shortcuts import redirect
from .models import UserProfiles
class UserProfileBackend(BaseBackend):
def authenticate(self, request, email=None, password=None):
try:
user = UserProfiles.objects.get(email=email)
if user.check_password(password):
return user
except UserProfiles.DoesNotExist:
return None
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>Vehicle Parking Management System - User Login</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,700&display=swap" rel="stylesheet">
<link rel="stylesheet" href="{% static 'styles/loginstyle.css' %} ">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand text-primary" href="#">Vehicle Parking Management System</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
</nav>
<div class="container mt-5">
<h1 class="text-center mb-5"><em><strong>Welcome to the Vehicle Parking Management System</strong></em></h1>
<div class="row">
<div class="col-md-6 offset-md-3">
<div class="card">
<div class="card-body">
<h5 class="card-title text-center">User Login</h5>
<form action="{% url 'parkingapp:userLogin' %}" method="POST">
{% csrf_token %}
<div class="form-group">
<label for="email">Email Address</label>
<input type="email" class="form-control" id="email" name='email' placeholder="Enter your email address">
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="password" name="password" placeholder="Enter your password">
</div>
{% if messages %}
<ul class="messages">
{% for message in messages %}
<li>{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li>
{% endfor %}
</ul>
{% endif %}
<button type="submit" class="btn btn-primary btn-block">Login</button>
</form>
<div class="text-center">
<p class="text-center">Don't have an existing account? <a href="{% url 'parkingapp:userSignup' %}" class="btn btn-link">Sign up here</a></p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="{% static 'js/loginscript.js' %}"></script>
</body>
</html>
I also tried this code , result is none
testuser = authenticate(username='[email protected]', password='sim')
print(testuser)
Then tried printing the data fetching from table, It is retrieving the email and password.
user = authenticate(request, username=email, password=password) print("from database ",user_profile.email,user_profile.password) print(user)
from loginhtml page [email protected] vim
from database [email protected] vim
None
None
2
Answers
I changed the model to Django's built in table auth user and changed the code according to that. It worked for me.
Here is my views.py
There are a few problems in your code. The main one being the
User
model. You are not using Django’s, which is a bad practice. Take a look at this example. I would recommend to rebuild your model based on this.Now, related to your current problem, that is happening because of the fields you are calling on
authenticate
and the fields you set in the custombackend
.views.py
backend.py
As you can see, you pass
username
as a param inauthenticate
, but try to catch it asemail
in your custom backend. And, sinceemail
is always none, so is theuser
, just modify the param accordingly:Although, even if you fix that, another error is raised because you are not using Django’s
User
model (missing a field required inlogin
). So we need to modify yours:models.py
And, of course add the backend to
AUTHENTICATION_BACKENDS
:settings.py