When and where i use create_user from CreateUserManager()?

For several days now, I've been wondering why I should create my own user manager in Django, since in the end, when inheriting a built-in form, I don't refer to my created manager anyway.

class CustomUserManager(BaseUserManager):

    def create_user(self, email, birth_date, password=None, **extra_fields):
        if not email:
            raise ValueError("You didn't entered a valid email address!")
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user
    
    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_stuff', True)
        extra_fields.setdefault('is_superuser', True)
        
        return self.create_user(email, password, **extra_fields)

I have something like this and in the end when it creates a user it doesn't go through that create_user anyway.

So my two questions:

  1. Why create something for a custom user if I don't end up using it anyway because the form inherits from UserCreationForm. So, for example, form.save() does not use my manager.

  2. At what point should this create_user be executed?

Q Why create something for a custom user if I don't end up using it anyway because the form inherits from UserCreationForm. So, for example, form.save() does not use my manager.

Answer to you Question

You need a custom user manager because Django’s default one won’t handle your custom fields properly like using email instead of a username.

Even though UserCreationForm doesn’t use it by default, your its still needed when you either want to create user manually, or to ensure superuser are setup correctly

Q2 At what point should this create_user be executed?

Answer You should call create_user when you need to create a user manually, e.g, in your views or .py script Django's UserCreationForm ignores it unless you override save(), so tweak the form or call create_user manually when adding users outside it.

Вернуться на верх