>": "Comment.user" must be a "MyProfile" instance-6ren"> >": "Comment.user" must be a "MyProfile" instance-您好,我知道这里有两个问题。一个是 SimpleLazyObject 问题,我可以用一种有点骇人听闻的方式解决它。另一个是“Comment.user”必须是一个“MyProfile”实例,我不知道如何-6ren">
gpt4 book ai didi

python - 无法分配 ">": "Comment.user" must be a "MyProfile" instance

转载 作者:行者123 更新时间:2023-11-28 22:38:27 25 4
gpt4 key购买 nike

您好,我知道这里有两个问题。一个是 SimpleLazyObject 问题,我可以用一种有点骇人听闻的方式解决它。另一个是“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)

我不确定 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')

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

最佳答案

评论有 ForeignKeyMyProfile,但在触发错误的行中您提供了一个 User 模型。正确的方法是:

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

请注意,您使用:

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

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

关于python - 无法分配 "<SimpleLazyObject: <User: XXX>>": "Comment.user" must be a "MyProfile" instance,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35567667/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com