我在Django中有一个扩展的UserProfile模型:
class UserProfile(models.Model): user = models.ForeignKey(User, unique=True) #other things in that profile
还有一个signal.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:中确保信号被注册:
__init__.py
import signals
因此,应该为每个注册用户创建一个新的UserProfile,对吗?但事实并非如此。尝试登录时,总是出现“ UserProfile匹配查询不存在”错误,这意味着该数据库条目不存在。
我应该说我使用django-registration,它提供了user_registered信号。
为此,重要应用程序的结构是,我有一个名为“用户”的应用程序,这里有:models.py,signals.py,urls.py和views.py(以及其他一些在这里无关紧要的东西) )。UserProfile类在models.py中定义。
更新:我将signals.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”:
"column user_id is not unique"
编辑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")
你可以在用户上使用post_save实现它:
from django.db.models.signals import post_save from models import UserProfile from django.contrib.auth.models import User def create_profile(sender, **kwargs): user = kwargs["instance"] if kwargs["created"]: profile = users.models.UserProfile() profile.setUser(sender) profile.save() post_save.connect(create_profile, sender=User)
编辑: 另一个可能的解决方案,它已经过测试并且可以正常工作(我正在我的网站上使用它):
from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save def create_profile(sender, **kwargs): user = kwargs["instance"] if kwargs["created"]: up = UserProfile(user=user, stuff=1, thing=2) up.save() post_save.connect(create_profile, sender=User)