【发布时间】:2012-03-07 23:16:06
【问题描述】:
我遵循了以下指南: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)
用户档案模型
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 的新手,尽管到目前为止 Google 一直很有帮助,但几个小时后我还没有征服它。如果需要有关此问题的更多信息,我很乐意提供!
谢谢。
编辑:
我发现可能有用的东西(但没有解决我的特定问题):
【问题讨论】:
标签: django django-models foreign-keys save user-profile