Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between User.objects.create_user() vs User.objects.create() vs User().save() in django

In the Django documentation, it uses User.objects.create_user() to create a user. I am confused, what is the difference between that and User.objects.create() and User().save() which are the normal ways to create objects of other models

like image 486
ahmed osama Avatar asked Jul 23 '20 13:07

ahmed osama


2 Answers

The most significant difference is that if you supply a password to the .create() method, it will be set verbatim on the user, and will not be usable to authenticate the user.

>>> user = User.objects.create(username="foo", password="bar")
>>> user.password
'bar'
>>> user.check_password("bar")
False

Instead, the create_user() method hashes the password argument, which is then.

>>> user = User.objects.create_user(username="foo", password="bar")
>>> user.password
'pbkdf2_sha256$120000$2pHBVu3tYYbK$ESG1nbUY2ZhEmstJ7Fzu1DioXmGYXiLw31YDkOGn9E0='
>>> user.check_password("bar")
True

See https://github.com/django/django/blob/master/django/contrib/auth/models.py#L145.

Some other 'tidying' is also done. See the rest of the function linked above.

like image 106
nimasmi Avatar answered Sep 25 '22 21:09

nimasmi


User.objects.create_user() is a helper function that provides helpful utilities to create a user that otherwise you would have to do yourself. As per the documentation:

Creates, saves and returns a User

The username and password are set as given. The domain portion of email is automatically converted to lowercase, and the returned User object will have is_active set to True.

If no password is provided, set_unusable_password() will be called.

The extra_fields keyword arguments are passed through to the User’s __init__ method to allow setting arbitrary fields on a custom user model.

Without create_user() you could create the functionality yourself using the methods you mentioned, but it provides useful processing and utility.

like image 23
SevvyP Avatar answered Sep 23 '22 21:09

SevvyP