无法分配&#34; <simplelazyobject:<user:=“”xxx =“”>&gt;&#34;:&#34; Comment.user&#34;必须是&#34; MyProfile&#34;例

时间:2016-02-23 02:25:29

标签: python django

您好我知道我有两个问题。一个是simpleLazyObject问题,我可以用一种hackish方式修复它。另一个是&#34; Comment.user&#34;必须是&#34; MyProfile&#34;我不知道如何修复的例子。我觉得在某个方面,事情变得混乱。

def post(request, slug):
        user = get_object_or_404(User,username__iexact=request.user)
        try:
            profile = MyProfile.objects.get(user_id=request.user.id)
            # if it's a OneToOne field, you can do:
            # profile = request.user.myprofile
        except MyProfile.DoesNotExist:
            profile = None
        post = get_object_or_404(Post, slug=slug)
        post.views += 1  # increment the number of views
        post.save()      # and save it
        comments = post.comment_set.all()
        comment_form = CommentForm(request.POST or None)
        if comment_form.is_valid():
            post_instance = comment_form.save(commit=False)
            post_instance.user = request.user #this is where error is occuring, if I put request.user.id simpleLazyObject dissapears.
            post_instance.path = request.get_full_path()
            post_instance.post = post
            post_instance.save()

        context_dict = {
            'post' :post,
            'profile' :profile,
            'comments':comments,
            'comment_form': comment_form
        }

        return render(request, 'main/post.html', context_dict)

我不确定comment.user必须是myprofile实例是什么意思。

在我的评论应用中,models.py我有

class Comment(models.Model):
    user = models.ForeignKey(MyProfile)

在我的帐户应用中,models.py我有

class MyProfile(UserenaBaseProfile):
    user = models.OneToOneField(User, unique=True, verbose_name=_('user'), related_name='my_profile')

我不确定如何解决这个问题,我们将非常感谢任何帮助...

1 个答案:

答案 0 :(得分:3)

注释具有ForeignKey到MyProfile,但在触发错误的行中,您提供了用户模型。 正确的方法是:

my_p = MyProfile.objects.get(user=request.user)
post_instance.user = my_p

请注意您使用:

MyProfile.objects.get(user=request.user)

而不是id字段。虽然在幕后django确实使用id字段作为数据库中的真正外键,但在您的代码中使用该对象。关系字段是一个描述符,其中django可以运行关系查询。