DEV Community

DoriDoro
DoriDoro

Posted on

Create a superuser in Django with custom user model attributes

If you create a custom User model, inherited from AbstractUser and add custom attributes, it will be difficult to create a superuser with command python manage.py createsuperuser in terminal.

An example custom User model inherited by AbstractUser:

# accounts/models.py

from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import gettext_lazy as _


class User(AbstractUser):
    """create User instance with additional attributes"""

    age = models.PositiveSmallIntegerField(
        default=15, validators=[MinValueValidator(15)], verbose_name=_("age")
    )
    can_be_contacted = models.BooleanField(verbose_name=_("contact consent"))
    can_data_be_shared = models.BooleanField(verbose_name=_("share consent"))
Enter fullscreen mode Exit fullscreen mode

In order to be able to create a superuser, you need to pass the additional attributes.

One simple solution is to create a superuser in django shell:

$ python3 manage.py shell
Enter fullscreen mode Exit fullscreen mode
Python 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from accounts.models import User
>>> from django.contrib.auth import get_user_model
>>> User = get_user_model()
>>> User.objects.create_superuser(username='Admin', email='admin@mail.com', password='custom_passW', age=30, can_be_contacted=True, can_data_be_shared=True)
<User: Admin>
Enter fullscreen mode Exit fullscreen mode

from accounts.models import User: You import the custom User model from the app: "accounts" and the file: "models.py"
User = get_user_model(): This method will return the currently active user model, says :Django docs
User.objects.create_superuser(username='Admin', email='admin@mail.com', password='custom_passW', age=30, can_be_contacted=True, can_data_be_shared=True): you use the create_superuser method with all attributes to create a superuser.
User: Admin: with this confirmation you have created a superuser with username Admin.

Top comments (0)