python - 使用 post_save 信号或执行 View 中的逻辑有什么区别

标签 python django django-views signals

所以我有以下代码:

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

from myapp.models import UserProfile

@receiver(post_save, sender=User)
def auto_create_profile(sender, **kwargs):
    instance = kwargs['instance']
    created = kwargs['created']
    if created:
        profile = UserProfile(foo=foo)
        profile.user = instance
        profile.save()

前面的代码和在注册 View 上创建配置文件有什么区别?

def some_view(request):
    #save the user and then
    profile = UserProfile(foo=foo, user=user)
    profile.save()

最佳答案

使用post_save,当以其他方式创建用户帐户时,也会创建用户个人资料,例如:

  • 使用manage.py shell控制台
  • 使用 django 管理
  • 使用其他 View
  • 使用第三方软件包,例如 python-social-auth

关于python - 使用 post_save 信号或执行 View 中的逻辑有什么区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33671417/

相关文章:

django - 从 Django View 将变量传递给远程(Golang)应用程序的最佳方法

jquery - Django 自动完成灯 : field not populated

Django、Ajax 长轮询、Postgresql : idle transaction

Python Shelf 能够创建但无法打开 Shelf

python - 如何在 python 中的 sqlalchemy.sql.expression.func.random() 中设置随机种子?

python - 在 python 中实现此工作流的最佳方式

python - 是否存在运算符(operator)错误,因为执行后它说不明确错误。我在做什么错误?

mysql - 如何使用 update() 在 Django 的日期时间字段上增加年份?

python - Django 的正则表达式 url 模式

python - 为什么我的 django 模板不输出模板变量对象?