简体   繁体   中英

How can I correctly make signals in django 3?

I have users app written on django3(python 3.8). and model Profile which is extending User model. So i wanna do that each time when user creates account, django automaticly makes Profile for this. I have signals.py file on user app:

from django.db.models.signals import post_save
from django.contrib.auth.models import User
from django.dispatch import receiver
from .models import Profile

@receiver(post_save, sender = User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user = instance)
@receiver(post_save, sender = User)
def save_profile(sender, instance, **kwargs):
    instance.profile.save()

and it's my users/apps.py:

from django.apps import AppConfig


class UsersConfig(AppConfig):
    name = 'users'
        
    def ready(self):
        import users.signals

All working, no exceptions, errors. But It doesnt create profiles for new users. note:

  1. i had wrote print() in the ready method. But it doesnt print.
  2. When i make profile in admin site, there are no problem. But why signals doesnt work?

First of all if you have changed your User model or trying to use some other model as your user model, don't forget to Add line AUTH_USER_MODEL = 'users.User' to your settings.py (change the 'users.User' to path of your User's app) to tell Django that you're using another model instead of default user model. Then in your signal instead of from django.contrib.auth.models import User try from django.contrib.auth import get_user_model and change your codes to something like:

from django.db.models.signals import post_save
from django.contrib.auth import get_user_model
from django.dispatch import receiver
from .models import Profile


User = get_user_model()


@receiver(post_save, sender = User)
def create_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user = instance)

Finally if you have already done these steps and you're signals still doesn't work try to add the following line in your __init__.py of your users app:

default_app_config = 'users.apps.UsersConfig'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM