cph2117 cph2117 - 4 months ago 20
Python Question

Django UserManager create_user failing with 'NoneType' object not callable

I followed the code in this custom Django user model example almost verbatim, and when I try to create a user it fails on the last parameter of

self.model
with the error

TypeError: 'NoneType' object is not callable


The relevant code snippet is below:

class MyUserManager(BaseUserManager):

def create_user(self, email, password=None,
first_name=None,
last_name=None
):
now = timezone.now()
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)

user = self.model(email=email,
first_name=first_name,
last_name=last_name
)

user.set_password(password)
user.save(using=self._db)
return user

class MyUser(AbstractBaseUser, PermissionsMixin):

email = models.EmailField(_('email address'), max_length=254, unique=True)
first_name = models.CharField(_('first name'), max_length=30, blank=False)
last_name = models.CharField(_('last name'), max_length=30, blank=False)

objects = MyUserManager()

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []

class Meta:
verbose_name = _('user')
verbose_name_plural = _('users')

def get_full_name(self):
"""
Returns the first_name plus the last_name, with a space in between.
"""
full_name = '%s %s' % (self.first_name, self.last_name)
return full_name.strip()


It looks like
self.model
is
None
, but I thought having the line
objects = MyUserManager()
in
MyUser
is what associated the two.

The traceback:

Traceback (most recent call last):
File "api/tests/test_location.py", line 24, in setUp
first_name=first_name, last_name=last_name)
File "api/models.py", line 99, in create_user
last_name=last_name
TypeError: 'NoneType' object is not callable


I call it like so:

MyUserManager().create_user(email=email, password=password, first_name=first_name,
last_name=last_name)

Answer

There will be no model instance attached to that instance of MyUserManager if you instantiate it directly and call the create_user method like so. You should instead make the call from your MyUser model:

my_user = MyUser.objects.create_user(email=email, 
                                     password=password, 
                                     first_name=first_name, 
                                     last_name=last_name)