Im trying to register users hashing their passwords before add to database as follows
settings.py
PASSWORD_HASHERS = (
'django.contrib.auth.hashers.MD5PasswordHasher',
)
Models.py
from django.contrib.auth.models import AbstractBaseUser
class Users(AbstractBaseUser):
name = models.CharField(max_length=200)
email = models.CharField(max_length=200)
password = models.CharField(max_length=255)
Views.py
name = form.cleaned_data.get('name')
email = form.cleaned_data.get('email')
password = form.cleaned_data.get('password')
date_joined = date.today()
if Users.objects.filter(email=email).exists() and Users.objects.filter(name=name).exists() :
messages.info(request, 'User already exists')
else:
Users.objects.create(name=name, email=email, password=set_password(password), date_joined=date_joined)
but when i actually trying to create the user i get Python : name 'set_password' is not defined
What is wrong? do i need to import something at Views.py
?
You must use set_password()
on a user instance, not when creating a user.
Try this:
user = Users.objects.create(name=name, email=email, date_joined=date_joined)
user.set_password(password)
user.save()
I can see you are extending the user model. I'd have a look at some articles for ways to do this, I recommend this article.
Perfect. Thank you very much! At the login state do i repeat the same process?
Its a different process, you can just use the password from the form. Have a look at the docs here: docs.djangoproject.com/en/3.1/topics/auth/default/…
i think
authenticate()
checks for the unhashed password. This is not working in my caseauthenticate()
does not check for the unhashed password. The password is never stored in the DB as unhashed since you have set:'django.contrib.auth.hashers.MD5PasswordHasher'
. It will hash the password from the form and check if the hashed form password matches the hashed password in the DB. This way, the password in the DB is never "unhashed".