Search code examples
djangodjango-modelsdjango-users

Foreign key in custom user manager


I'm trying to create a custom user model in django, using a ForeignKey as required_field. My Manager is as follows:

from django.contrib.auth.models import BaseUserManager

from .models import State
class CustomUserManager(BaseUserManager):
    def create_user(self, email, first_name, state, password=None, **extra_fields):
        email = self.normalize_email(email)
        user = self.model(email=email, first_name=first_name, state=State(pk=state), **extra_fields)
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, first_name, state, password=None, **extra_fields):
        email = self.normalize_email(email)
        user = self.model(email=email, first_name=first_name, state=State(pk=state), **extra_fields)
        user.set_password(password)
        user.save()
        return user

When trying to use createsuperuser via manage.py, the following exception happens

from .models import State
ImportError: cannot import name 'State' from 'account.models'

The State class exists in account.models, the module is called account

I don't know how else to create the user, as a State instance is required.


Solution

  • The user model imports from this module to set User.objects = CustomUserManager(). You can move State to a different module/app or move this manager definition into models.