How to override createsuperuser command in django

Question:

I’m trying to customize the createsuperuser command.

The purpose of this is:

I’ve a table called administrator, and its have OneToOne relationship with auth_user table

class Administrator(models.Model):
    user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, related_name="admin")

And whenever I create new super user by using command createsuperuser, i’d like to create a record in table administrator as well.

But I’m not sure how to do this yet.
Please help, thanks.

Here’s my repo:

https://github.com/congson95dev/regov-pop-quiz-backend-s-v1/blob/main/auth_custom/management/commands/createsuperuser.py

Asked By: fudu

||

Answers:

The thing you are trying to achieve can be done easily via signals. Signals are very useful and they are fired when there is any change in database or when an object is created in django models .

in your app ( any app you want where you have your admin table ) create signals.py file.

signals.py

from django.signals import receiver
from django.db.models.signals import post_save
from django.contrib.auth.models import User
# from yourapp.models import Administrator

@receiver(post_save , sender = User)
def saveAdminUserForSuperUser(sender , instance , created , **kwargs):
    # instance is the object of the User model which has just been created and it fired this signal .
    if created and instance.is_superuser  :
        admin = Administrator.objects.create(user = instance)
        admin.save()

# This will create an object in admin table for the super user . 

After this you need to register your signals which is done in the apps.py for the app

your app.py where you have created your signals.py file

from django.apps import AppConfig

class YourAppConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'yourapp'

    def ready(self):
        import yourapp.signals

You do not need to write the class and all , you just need to create a new function inside the class named ready and import the file signals.py which you have created in the app .

Make sure you add the ready function and import the signals.py from the same app where you have your signals.py .

Answered By: Om Kashyap