2

I am making a custom user model using the AbstractBaseUser and PermissionsMixin by following these two tutorials (tutorial-1 and tutorial-2).

This the model so far:

class User(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField('email address', unique=True, db_index=True)
    username = models.CharField('username', unique=True, db_index=True)
    joined = models.DateField(auto_now_add=True)
    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)

    USERNAME_FIELD = 'email'

    def __unicode__(self):
        return self.email

Now what I am confused about is that in tutorial-1, the author didn't made any custom manager for the custom User model. Instead he use forms for creating user.

class RegistrationForm(forms.ModelForm):
    email = forms.EmailField(label = 'Email')
    password1 = forms.CharField(widget = forms.PasswordInput(), label = "Password")
    password2 = forms.CharField(widget = forms.PasswordInput(), label = 'Retype password')

    class Meta:
        model = User
        fields = ['email', 'username', 'password1', 'password2']

    def clean(self):
        """
        Verify that the values entered into the password fields match
        """
        cleaned_data = super(RegistrationForm, self).clean()
        if 'password1' in self.cleaned_data and 'password2' in self.cleaned_data:
            if self.cleaned_data['password1'] != self.cleaned_data['password2']:
                raise ValidationError("Password don't match.")
        return self.cleaned_data

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.set_password(self.cleaned_data['password1'])
        if commit:
            user.save()
        return user

But in tutorial-2, its author made a custom manager for the custom User model.

class UserManager(BaseUserManager):

    def create_user(self, email, password, **kwargs):
        user = self.model(
            email=self.normalize_email(email),
            is_active=True,
            **kwargs
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, password, **kwargs):
        user = self.model(
            email=email,
            is_staff=True,
            is_superuser=True,
            is_active=True,
            **kwargs
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

Referencing with Django Docs, there's an example of custom user model, and it uses custom manager. My question is, whether it is ok not to make any other custom manager and if not what is the use of creating a custom manager?

Benjamin Smith Max
  • 2,668
  • 8
  • 33
  • 56

1 Answers1

1

I think this is the relevant section from the docs for you:

You should also define a custom manager for your User model. If your User model defines username, email, is_staff, is_active, is_superuser, last_login, and date_joined fields the same as Django’s default User, you can just install Django’s UserManager; however, if your User model defines different fields, you will need to define a custom manager that extends BaseUserManager providing [the create_user() and create_superuser() methods].

The example in the docs needs to define a custom manager, so that it can set the date_of_birth field.

It appears that the example in the tutorial requires a custom manager, because it uses the email as the unique identifier, and does not have a separate username field.

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • Yes, that I got now, thank you. But I am still confused, because in tutorial-1, he is using `USERNAME_FIELD` as an email, but he didn't made another custom manager to handle that. Could you please help me with this. Thank you. – Benjamin Smith Max Oct 09 '15 at 15:07
  • If you [look at this comment](http://blackglasses.me/2013/09/17/custom-django-user-model/#comment-1527045990) on the first tutorial, it looks to me like it was a mistake to leave out the manager. – Alasdair Oct 09 '15 at 15:17
  • Ok. I think I am following now. Thank you so much for your help. – Benjamin Smith Max Oct 09 '15 at 17:18