My Case
In my case User is the default django user model and I've created a Profile to add more details to the User model.
To achieve
Now what i want is that whenever I create a new User a Profile for that user should automatically get created.
I've done
1. I have checked my signals.py file and also imported the signals in apps.py file but still nw Profile is not being created for each new user being created :(
2. Tried adding 'users.apps.UsersConfig' to my INSTALLED_APPS and it didn't work out as well.
Code below
I have provided the code in my signals.py and apps.py file below.
Please ask me if you need some more code
and thanks in advance :)
Here is my signals.py file
#This is the signal that will be sent
from django.db.models.signals import post_save
#This is the object which will send the signal
from django.contrib.auth.models import User
#This will receive the signal
from django.dispatch import receiver
#We need this to perform operations on profiles table
from .models import Profile
#This function creates new profile for each user created
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
#This function saves those newly created profiles
@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
Here is my apps.py file
from django.apps import AppConfig
class UsersConfig(AppConfig):
name = 'users'
def ready(self):
import users.signals
Here are my INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#Custom Apps
'product',
'shop',
'market',
'pages',
'users',
]
I was using 'users' in INSTALLED_APPS instead of 'users.apps.UsersConfig'.
My new working INSTALLED_APPS looks like this:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#Custom Apps
'product',
'shop',
'market',
'pages',
'users.apps.UsersConfig', #Signals wont work if you just write 'users'
]
Or just refer to a similar question :
https://stackoverflow.com/a/59028716/11687381