我在 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
所以这应该为每个注册的用户创建一个新的用户配置文件,对吧?但事实并非如此。当我尝试登录时,我总是收到“用户配置文件匹配查询不存在”错误,这意味着数据库条目不存在。
我应该说我使用 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")