无法分配“<SimpleLazyObject:<用户:XXX>>”:“Comment.user”必须是“MyProfile”实例

win*_*xee 2 python django

您好,我知道我在这里有两个问题。一个是 simpleLazyObject 问题,我可以用有点 hackish 的方式修复它。另一个是“Comment.user”必须是我不知道如何修复的“MyProfile”实例。我认为在某种程度上,事情变得混乱了。

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)
Run Code Online (Sandbox Code Playgroud)

我不确定评论是什么意思。用户必须是 myprofile 实例。

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

class Comment(models.Model):
    user = models.ForeignKey(MyProfile)
Run Code Online (Sandbox Code Playgroud)

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

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

我不知道如何解决这个问题,任何帮助将不胜感激...

Avi*_*aor 5

评论具有 MyProfile 的外键,但在触发错误的行中,您提供了用户模型。正确的方法是:

my_p = MyProfile.objects.get(user=request.user)
post_instance.user = my_p
Run Code Online (Sandbox Code Playgroud)

请注意,您使用:

MyProfile.objects.get(user=request.user)
Run Code Online (Sandbox Code Playgroud)

而不是 id 字段。尽管在幕后 django 确实使用 id 字段作为数据库中的真正外键,但在您的代码中您使用了对象。关系字段是一个描述符,django 在其中发挥了运行关系查询的魔力。