2 回答

TA貢獻1820條經驗 獲得超10個贊
創建一個 signal.py 文件,然后在其中添加以下代碼:
from django.contrib.auth.models import User
from django.db.models.signals import post_save
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()
然后在您的用戶 apps.py 中添加以下代碼:
class UsersConfig(AppConfig):
name = 'users'
def ready(self):
import users.signals
那么你就完成了!

TA貢獻1847條經驗 獲得超7個贊
假設您有一個名為“profiles”的應用程序profiles/signals.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from profiles.models import Profile
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.profile.save()
在profiles/app.py
from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class ProfilesConfig(AppConfig):
name = 'cmdbox.profiles'
verbose_name = _('profiles')
def ready(self):
import cmdbox.profiles.signals # noqa
終于在profiles/__init__.py
default_app_config = 'profiles.apps.ProfilesConfig'
添加回答
舉報