1π
β
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.dispatch 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 .
π€Om Kashyap
Source:stackexchange.com