Sometimes i want to set the password programmatically. I do the following:
https://docs.djangoproject.com/en/2.2/topics/auth/default/#changing-passwords
You can also change a password programmatically, using set_password():
from django.contrib.auth.models import User
u = User.objects.get(username='john')
u.set_password('new pass')
u.save()
I wanted to see how things are implemented in save() when we run u.save()
Basically I am trying to understand the save() method used in AbstractBaseUser
# ./.venv/lib/python3.7/site-packages/django/contrib/auth/base_user.py
class AbstractBaseUser(models.Model):
password = models.CharField(_('password'), max_length=128)
........
# Stores the raw password if set_password() is called so that it can
# be passed to password_changed() after the model is saved.
_password = None
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
if self._password is not None:
password_validation.password_changed(self._password, self)
self._password = None
........
def set_password(self, raw_password):
self.password = make_password(raw_password)
self._password = raw_password
Here in def save(self, *args, **kwargs):
super().save(*args, **kwargs)
will save the password set by set_password before the next lines password_validation.password_changed which validate the password
So what is the point in saving the password first and then validating afterwards, because it's already gone into the database.