self.model() in django custom UserManager
Asked Answered
N

1

17

So, I'm fairly new to Django. Notwithstanding the fact that my code works after following the Django docs 'Customizing authentication in Django', I don't get how the self.model(...) in their example actually works, where it comes from and how it functions with 'self'.

This is the example found at the bottom of the docs.

from django.db import models

from django.contrib.auth.models import (
    BaseUserManager, AbstractBaseUser
)

class MyUserManager(BaseUserManager):
    def create_user(self, email, date_of_birth, password=None):
        """
        Creates and saves a User with the given email, date of
        birth and password.
        """
        if not email:
            raise ValueError('Users must have an email address')

   ->   user = self.model(
            email=self.normalize_email(email),
            date_of_birth=date_of_birth,
        )

        user.set_password(password)
        user.save(using=self._db)
        return user
...
Newmodel answered 3/7, 2018 at 21:35 Comment(1)
Something that uses models, calls the add_to_class class method of ModelBase (which all models have as a meta-class) which calls contribute_to_class of BaseManager (which all managers inherit from) which sets the model field.Aoristic
L
27

Well, what you define here is a MyUserManager class. This inherits from the BaseUserManager class [GitHub]. This is a subclass of the Manager class [GitHub]. You actually use manager all the time. For example SomeModel.objects is a manager.

A manager has, if it is used, a reference to the model it manages. So SomeModel.objects is a manager, but that manager has an attribute .model that actually refers back to the SomeModel class.

Now a class in Python is typically callable. If you for example call int('42'), you call the int(..) constructor. In this case your self.model will - by default - by the User model (although that can be overwritten).

Now in Django the constructor of a model takes, named parameters, to construct a model instance. If you write User(date_of_birth=date(2018, 7, 3), email='[email protected]'), then you construct an unsaved User instance with as field values July 3rd 2018 as date_of_birth, and '[email protected]' as email.

So here you typically construct a User instance (or an instance of another model you used to represent Users). You then later use user.save() to save that instance to the database, and return it.

Larissa answered 3/7, 2018 at 21:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.