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
...
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 User
s). You then later use user.save()
to save that instance to the database, and return it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With