0
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager

class UserManager(BaseUserManager):
    def create_user(self, email, password=None, is_active=True, is_staff=False, is_admin=False):
        if not email:
            raise ValueError("Users must have an email address")
        if not password:
            raise ValueError("Users must have password")

        user = self.model(
            email = self.normalize_email(email)
        )
        user.set_password(password) #change user password
        user.staff = is_staff
        user.admin = is_admin
        user.active = is_active
        user.save(using=self._db)
        return user
    
    def create_staffuser(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_staff=True
        )
        return user
    
    def create_superuser(self, email, password=None):
        user = self.create_user(
            email,
            password=password,
            is_staff=True,
            is_admin=True
        )
        return user

class User(AbstractBaseUser):
    email = models.EmailField(max_length=255, unique=True)
    full_name = models.CharField(max_length=255, blank=True, null=True)
    active = models.BooleanField(default=True) #can login
    staff = models.BooleanField(default=False) #staff user non superuser
    admin = models.BooleanField(default=False) #superuser
    timestamp = models.DateTimeField(auto_now_add=True)

    USERNAME_FIELD = 'email' #username
    #email and password required by default
    REQUIRED_FIELDS = []

    def __str__(self):
        return self.email

    def get_full_name(self):
        return self.email
    
    def get_short_name(self):
        return self.email
    
    @property
    def is_staff(self):
        return self.staff
    
    @property
    def is_admin(self):
        return self.admin
    
    @property
    def is_active(self):
        return self.active

I tried following a video on how to create a custom user model, but when I tried to create a superuser, I got the following error after entering my email:

You have 1 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): accounts.
Run 'python manage.py migrate' to apply them.
Email: abc123@gmail.com
Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    main()
  File "manage.py", line 18, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\baris\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line     
    utility.execute()
  File "C:\Users\baris\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\__init__.py", line 395, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\baris\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\base.py", line 330, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\baris\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute
    return super().execute(*args, **options)
  File "C:\Users\baris\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\core\management\base.py", line 371, in execute
    output = self.handle(*args, **options)
  File "C:\Users\baris\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 113, in handle
    error_msg = self._validate_username(username, verbose_field_name, database)
  File "C:\Users\baris\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 234, in _validate_username
    self.UserModel._default_manager.db_manager(database).get_by_natural_key(username)
AttributeError: 'Manager' object has no attribute 'get_by_natural_key'

It first tells me there is an unapplied migration and that the 'Manager' object has no 'attribute get_by_natural_key'. If I try to migrate I get another error and I don't know what these errors mean, please help me if you do!

TypeError: expected string or bytes-like object

  • For starters you should apply all your migrations. What happens when you do `python manage.py migrate` like it says? – Toni Sredanović Feb 12 '21 at 19:08
  • 4
    Does this answer your question? [AttributeError: 'Manager' object has no attribute 'get\_by\_natural\_key' error in Django?](https://stackoverflow.com/questions/14723099/attributeerror-manager-object-has-no-attribute-get-by-natural-key-error-in) – Safiul Kabir Feb 12 '21 at 19:48
  • I have tried migrating it, but I keep getting the following error: "TypeError: expected string or bytes-like object". I tried changing the name for the class User (because I thought that might not be allowed or something) to MyUser, but then I got a different error saying: "ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'accounts.myuser', but app 'accounts' doesn't provide model 'myuser'". I have read the other page, but there it said I need to define a BaseUserManager if I want a custom user model, but I already have that. So I don't know what's wrong! – Baris Savci Feb 13 '21 at 00:19

0 Answers0