我遵循了以下指南:http://www.turnkeylinux.org/blog/django-profile并且它工作得很漂亮,除了我似乎无法将ForeignKey保存到用户配置文件中。
PCBuild模型
from django.contrib.auth.models import User
from django.db import models
class PCBuild(models.Model):
name = models.CharField(max_length=50)
owner = models.ForeignKey(User)
UserProfile模型
import datetime
import md5
from apps.pcbuilder.models import PCBuild
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
user = models.OneToOneField(User)
email_hash = models.CharField(max_length=200) #MD5 hash of e-mail
current_build = models.ForeignKey(PCBuild,
related_name='current_build', null=True, blank=True)
def __unicode__(self):
return self.user.email
User.profile = property(lambda u: UserProfile.objects.get_or_create(
user=u,
email_hash=md5.new(u.email).hexdigest())[0])
>>> from django.contrib.auth.models import User
>>> from apps.pcbuilder.models import PCBuild
>>> from django.shortcuts import get_object_or_404
>>> user = get_object_or_404(User, pk=2)
>>> user
<User: Trevor>
>>> pcbuild = get_object_or_404(PCBuild, pk=11)
>>> pcbuild
<PCBuild: StackOverflowBuild>
>>> pcbuild.owner
<User: Trevor>
>>> user.profile.email_hash
u'd41d8cd98f00b204e9800998ecf8427e'
>>> user.profile.current_build = pcbuild
>>> user.profile.save()
>>> user.profile.current_build
# nothing is stored/outputted - this is the problem!
我是Django的新手,虽然谷歌到目前为止一直很有帮助,但这个我几个小时后都没有征服过。如果需要有关此问题的更多信息,我很乐意提供!
感谢。
修改
我发现的东西可能有用(但没有解决我的特定问题):
答案 0 :(得分:1)
你将通过使用该属性遇到神秘的错误。由于UserProfile
到User
关系是OneToOneField
,因此您可以通过user.userprofile
从实例访问配置文件实例。如果您想更改名称,可以更新OneToOneField
的{{1}}媒体资源。
使用信号在创建用户时自动创建配置文件:
related_name
答案 1 :(得分:0)
我明白了 - 但我仍然愿意接受其他答案。将在稍后回来查看。我很确定它与我用来获取配置文件的lambda函数有关。我是如何在python shell中进行的:
>>> from django.contrib.auth.models import User
>>> from apps.pcbuilder.models import PCBuild
>>> from django.shortcuts import get_object_or_404
>>> user = get_object_or_404(User, pk=2)
>>> user
<User: Trevor>
>>> pcbuild = get_object_or_404(PCBuild, pk=11)
>>> pcbuild
<PCBuild: StackOverflowBuild>
>>> user.profile.current_build
# nothing (which is expected as there is nothing
# yet in the current_build of this user profile)
# NOTE: I'm creating a new "profile" variable that holds the user profile.
>>> profile = user.profile
>>> profile
<UserProfile: Trevor>
>>> profile.current_build
# nothing (which is expected as there is nothing
# yet in the current_build of this user profile)
>>> profile.current_build = pcbuild
>>> profile.save()
>>> user.profile.current_build
<PCBuild: StackOverflowBuild>
# As you can see, it worked!
我基本上必须将 user.profile 分配给它自己的变量(示例中为 profile ),然后在修改变量后,保存而不是用户对象
看起来有点尴尬,但它确实有效。