python - 为什么 post_save 信号在这里不起作用?
问题描述
我创建了一个在创建用户时创建配置文件的信号。以前,相同的代码在其他项目中运行良好。在这里,我不知道我做错了什么,它不起作用并且没有为创建的用户创建配置文件。这就是信号。
@receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
print(instance)
if created:
Profile.objects.create(user=instance)
@receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
所有导入都正确完成,在这里我将其导入到我的应用程序中:
class UsersConfig(AppConfig):
name = 'users'
def ready(self):
import users.signals
如果您想查看配置文件模型:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='profile_pics')
def __str__(self):
return "{} Profile".format(self.user.username)
由于我创建了一个信号,因此对于所有新创建的用户,它应该将其添加default.jpg
为默认个人资料图片。
但是,如果我创建一个新用户,登录然后转到个人资料页面,它会显示如下内容:
如果我去管理员并手动添加此个人资料图片,它就可以正常工作。最后一件事我还添加了以下设置urls.py
:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
请帮我修复它,我尝试了所有可能的方法已经 3 小时,但无法使其正常工作。谢谢您的帮助。
编辑:
template
<div class="media">
<img class="rounded-circle account-img" src="{{ user.profile.image.url }}">
<div class="media-body">
<h2 class="account-heading">{{ user.username }}</h2>
<p class="text-secondary">{{ user.email }}</p>
</div>
</div>
解决方案
src(unknown)
如果您没有profile
附加到您的用户,就会发生这种情况。这很可能意味着您的信号没有被触发,这是因为它们没有被加载,这是因为您的UsersConfig
应用程序没有被首先加载。
有两种加载应用程序的方式。适当的将是:
INSTALLED_APPS = [
# ...
'yourapp.apps.UsersConfig'
]
另一种方法是设置default_app_config = 'yourapp.apps.UsersConfig'
在yourapp/__init__.py
. 请注意,不再推荐用于新应用程序。
之后,您可能还想修改signals.py
- 如果您尝试保存Users
未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):
if hasattr(instance, 'profile'):
instance.profile.save()
else:
Profile.objects.create(user=instance)
推荐阅读
- c - 水果有时会消失 C中的蛇
- node.js - NestJS 架构 - 良好实践
- batch-file - xcopy 在命令提示符下工作,但在使用变量的批处理文件中失败
- javascript - 在创建的内部调用 axios 方法是否正确?
- javascript - Webpack-dev-server 抛出有关 node_modules/webpack-dev-server 中缺少的文件的错误
- python-3.x - 搜索关键字列并仅匹配找到的第一个子字符串
- python - 如何检查文件夹是否在 Windows/Macintosh 中打开并可能关闭它?
- javascript - 如何刷新 ag-grid 中的单个单元格
- curl - 如何在 Mac 上使用 CURL 安装 Heroku?tar 文件出错
- javascript - 试图弄清楚为什么时钟没有重置并且顶部弹出的气球没有在游戏中显示