【发布时间】:2010-12-26 23:47:19
【问题描述】:
我在 django 中有一个扩展的 UserProfile 模型:
class UserProfile(models.Model):
user = models.ForeignKey(User, unique=True)
#other things in that profile
还有一个signals.py:
from registration.signals import user_registered
from models import UserProfile
from django.contrib.auth.models import User
def createUserProfile(sender, instance, **kwargs):
profile = users.models.UserProfile()
profile.setUser(sender)
profile.save()
user_registered.connect(createUserProfile, sender=User)
我确保通过在我的__init__.py 中注册信号:
import signals
所以这应该为每个注册的用户创建一个新的用户配置文件,对吧?但事实并非如此。我在尝试登录时总是收到“UserProfile 匹配查询不存在”错误,这意味着数据库条目不存在。
我应该说我使用 django-registration,它提供了 user_registered 信号。
为此,重要应用程序的结构是,我有一个名为“用户”的应用程序,我有:models.py、signals.py、urls.py 和 views.py(以及其他一些不应该的东西)在这里没关系)。 UserProfile 类在 models.py 中定义。
更新:我将 signals.py 更改为:
from django.db.models.signals import post_save
from models import UserProfile
from django.contrib.auth.models import User
def create_profile(sender, **kw):
user = kw["instance"]
if kw["created"]:
profile = UserProfile()
profile.user = user
profile.save()
post_save.connect(create_profile, sender=User)
但现在我得到一个“IntegrityError”:
“列 user_id 不唯一”
编辑 2:
我找到了。看起来我以某种方式注册了信号两次。此处描述了解决方法:http://code.djangoproject.com/wiki/Signals#Helppost_saveseemstobeemittedtwiceforeachsave
我必须添加一个 dispatch_uid,现在我的 signals.py 看起来像这样并且正在工作:
from django.db.models.signals import post_save
from django.contrib.auth.models import User
from models import UserProfile
from django.db import models
def create_profile(sender, **kw):
user = kw["instance"]
if kw["created"]:
profile = UserProfile(user=user)
profile.save()
post_save.connect(create_profile, sender=User, dispatch_uid="users-profilecreation-signal")
【问题讨论】:
-
你能发布你的 django 应用程序的结构吗?我很好奇你代码中的几行,比如
profile=user.models.UserProfile()——你有一个名为“用户”的模块吗? UserProfile() 位于何处。 -
是用户,我不知道那个错字是怎么进来的,但问题是一样的。我想知道为什么 python 没有为拼写错误的路径抛出错误。
-
感谢这个解决方案,我是 django 的新手,我不知道如何保存有关用户配置文件的其他数据。我看到您只是将用户保存在模型 UserProfile 中,但是如何从注册表单中保存其他人的数据(使用您的信号.py)?谢谢(对不起英语)
标签: django django-registration