猿问

创建一个 post_save 信号,为我创建一个配置文件对象

下午好,我的用户模型中有以下信号,但在创建用户时它没有创建配置文件对象,这是我做错的。


  def create_profile(sender, instance, created, **kwargs):

    if created:

        Profile.objects.create(user=instance)


def save_profile(sender, instance, **kwargs):

    instance.create_profile.save()


post_save.connect(create_profile, sender=User)

post_save.connect(save_profile, sender=User)


万千封印
浏览 5289回答 2
2回答

拉莫斯之舞

创建一个 signal.py 文件,然后在其中添加以下代码:from django.contrib.auth.models import Userfrom django.db.models.signals import post_savefrom django.dispatch import receiverfrom .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那么你就完成了!

aluckdog

假设您有一个名为“profiles”的应用程序profiles/signals.pyfrom django.contrib.auth.models import Userfrom django.db.models.signals import post_savefrom django.dispatch import receiverfrom 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.pyfrom django.apps import AppConfigfrom 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__.pydefault_app_config = 'profiles.apps.ProfilesConfig'
随时随地看视频慕课网APP

相关分类

Python
我要回答