如何保存具有一对一字段的模型对象?

时间:2019-02-20 11:56:48

标签: django

我想通过单击按钮将评论保存到任何帖子,但是我收到错误消息: 在/ user_add_comment的 ValueError 禁止使用save()来防止由于未保存的相关对象'profile_user'而导致数据丢失。

型号:

    class UserProfileInfo(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        bio = models.TextField(max_length=100, blank=True, default="Bio")
        profile_pic = models.ImageField(upload_to='profile_users', blank=True)

        def __str__(self):
            return self.user.username


class CommentPostModel(models.Model):
    profile_user = models.OneToOneField(UserProfileInfo, on_delete=models.CASCADE)
    post = models.ForeignKey(PostModel, on_delete=models.CASCADE, related_name="comments")
    text = models.TextField(verbose_name="Text")
    comment_time = models.DateTimeField(default=datetime.now)
    approved = models.BooleanField(default=False)

    def approve(self):
        self.approved = True
        self.save()

    def __str__(self):
        return self.text

视图:

def user_add_comment(request):
      post_pk = request.GET.get('post_pk', None)
      post = PostModel.objects.get(pk=post_pk)
      user_info = UserProfileInfo.objects.filter(user=request.user)
      user_info2 = UserProfileInfo()
      for temp_user_info in user_info:
         user_info2 = temp_user_info
      break
      comment_text = request.GET.get('post_text', None)
      comment = CommentPostModel(profile_user=user_info2, post=post, 
      text=comment_text)
      comment.save()
      data = {
      "url": "/profile_page",
      }
      return JsonResponse(data)

1 个答案:

答案 0 :(得分:0)

您没有保存user_info2对象。所以像这样更改它:

for temp_user_info in user_info:
         user_info2 = temp_user_info
         user_info2.save()

编辑

根据您的要求,您可以像这样更改代码

def user_add_comment(request):
      post_pk = request.GET.get('post_pk', None)
      post = PostModel.objects.get(pk=post_pk)
      user_info = UserProfileInfo.objects.get(user=request.user)
      comment_text = request.GET.get('post_text', None)
      comment = CommentPostModel(profile_user=user_info, post=post, 
                                 text=comment_text
                                )
      comment.save()
      data = {
      "url": "/profile_page",
      }
      return JsonResponse(data)