Reputation: 3
I created a model called Driver
, which isn't inheriting from the in-built User model every django project comes with. Another model I created inherits from it. Each driver has a name, email and phone number. The model doesn't inherit the set_password()
or check_password()
functions from the User model so I had to make some additions to the model to save the hashed password. However, any time I test a login, it doesn't work, on account of the typed password not matching the hash in the database.
from django.db import models
from django.contrib.auth.hashers import make_password
class Driver(models.Model):
name = models.CharField(max_length= 50)
phone_number = models.CharField(max_length=15)
email = models.EmailField(unique=True, null=True)
password = models.CharField(max_length=50)
def __str__(self):
return self.name
def save(self, *args, **kwargs):
# Hash the password before saving
self.password = make_password(self.password)
super().save(*args, **kwargs)
def check_password(self, password):
return self.password == password
How can I create a function to properly compare the typed passwords to the hashed version in the database? Or am I going about this all wrong?
Upvotes: 0
Views: 20
Reputation: 5669
This check is incorrect
def check_password(self, password):
return self.password == password
as you check raw password with hashed on. When you do
make_password(self.password)
It hashes password.
So you need to compare:
return self.password == make_password(password)
But I urge you to use Django build in functionality.
Upvotes: 1