User creation - set_password

Hi everyone !

First of all, thanks a lot for this fantastic framework !!

I have some doubts about creating new users and hashing passwords.

I don’t understand if and when the set_password function is called when I manually create a user with the user.full_clean() and user.save() methods. If I read the documentation correctly, set_password is called when get_user_model().objects.create_user() is called. But I don’t read that this method is used with user.full_clean() or user.save().

I’d like to be sure that the passwords are actually hashed before saving a user instance.

Welcome @AAAA !

If you’re creating your own form for creating users, it’s up to you to call set_password when creating the object in your view.

You might want to look at how the Django Admin view works for adding a new user. It’s a bit intricate, but you would want to see django.contrib.auth.admin.UserAdmin, django.contrib.auth.forms.BaseUserCreationForm, and SetPasswordMixin. You could also build your new user form by inheriting from BaseUserCreationForm if your user model is sufficiently close to the default User model.

Whatever you do, you do not want to have a form field named password, if you’re using a ModelForm. You don’t want to introduce any possibility of directly storing the submitted password. You will always want to have that field as a “form-only” field and not a model field.

3 Likes

Thank you very much! Especially for the precision of your answer :slight_smile:

I wrote special methods to create users and also make my own authentication with DRF.

I’m going to do some refractoring to make sure I didn’t forget to call set_password.

Thanks again for everything