6

I searched, but could not find a proper answer for this. Currently in django we have three ways to create a User with custom manager-

1) By creating object instance and calling save() on it-

u = User(name="some_name", password="some_password")
u.save()

2) By calling create() on manager-

u = User.objects.create(name="some_name", password="some_password")

3) By calling create_user() on manager-

u = User.objects.create_user(name="some_name", password="some_password")

Information such as how each of them works internally and how they are similar and different, will be really helpful.

Saurabh Goyal
  • 605
  • 4
  • 21
  • See [this answer](https://stackoverflow.com/questions/11544398/user-manager-methods-create-and-create-user). – Ivan Sep 19 '15 at 11:52

2 Answers2

6

Methods 1) and 2) are generic methods to create a model instance. They do not do anything specific to the User model.

This means that the value you set as a password is not hashed, but is saved as-is. Django won't recognize is as a properly salted and hashed password, and you won't be able to login.

To properly set a password, use User.set_password():

u = User(name="some_name")
u.set_password("some_password")
u.save()

Note that you can't do the same with method 2) without an additional database query.

Method 3) is a convenience function that handles all the specifics of the User model, like hashing the password.

knbk
  • 52,111
  • 9
  • 124
  • 122
2

1) and 2) are identical in terms of what they do. The difference is that with method 1 you explicitly choose when to commit the object to the database with save.

Regarding 3, this is from the docs:

create_user(username, email=None, password=None, **extra_fields)

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.

So create_user looks like it applies a lowercase filter to the email, and sets an unusable password (preventing the user from being able to log in).

Isaac
  • 1,371
  • 3
  • 14
  • 36
  • An unusable password and a random password are not the same. An unusable password is saved as a specific token that disallows any login whatsoever. – knbk Sep 19 '15 at 11:54