【问题标题】:UserProfile model isn't saving ForeignKeysUserProfile 模型不保存 ForeignKeys
【发布时间】: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


    【解决方案1】:

    您将在使用该属性的情况下遇到神秘的错误。由于UserProfileUser 的关系是OneToOneField,您可以通过执行user.userprofile 从实例访问配置文件实例。如果您想更改名称,可以更新OneToOneFieldrelated_name 属性。

    在创建用户时使用信号自动创建配置文件,如下所示:

    from django.contrib.auth.models import User
    from django.db.models.signals import post_save
    
    def create_profile(sender, **kwargs):
        """Create a UserProfile instance when a User is created."""
        u = kwargs['instance']
        if kwargs['created']:
            UserProfile.objects.get_or_create(
                            user=u, 
                            email_hash=md5.new(u.email).hexdigest())
    
    post_save.connect(create_profile, sender=User)
    

    【讨论】:

    • 啊,谢谢。我已经将所有内容从user.profile 更改为user.get_profile(),但如果我以后想更改名称,我会注意。
    【解决方案2】:

    我想通了 - 但我仍然愿意接受其他答案,稍后再回来查看。我很确定这与我用来获取配置文件的 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),然后在修改变量后保存它而不是用户对象.

    看起来有点尴尬,但确实有效。

    【讨论】:

    • 这将非常令人困惑/容易出错。只需删除该属性并使用user.get_profile()
    • @sdolan 我想我的问题是如果用户还没有 UserProfile 怎么办(lambda 函数的目的)?我会看看使用user.get_profile() 是否对已经有个人资料的用户有用。谢谢。
    • 是的,效果更好。随意发布它作为答案,我会接受它。我知道 lambda 函数有点可疑。
    • 在创建User 实例时使用信号创建一个。
    • 我添加了一个关于如何做的答案。
    猜你喜欢
    • 2012-11-03
    • 2012-06-20
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 2019-04-09
    • 2010-10-15
    • 2016-01-23
    • 1970-01-01
    相关资源
    最近更新 更多