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'
添加回答
举报