TypeError:int()参数必须是字符串,类似字节的对象或数字,而不是'DeferredAttribute'

时间:2019-03-03 05:05:14

标签: python django

我想在我的帖子详细信息页面中添加评论部分。为此,我在youtube上观看了相关教程。在这里,本教程使用基于函数的视图,我想使其成为基于类的视图。 谁能帮我将其转换为基于类的视图

  

在基于函数的视图中

def post_detail(request, slug=None):
    instance = get_object_or_404(Post, slug=None)
    content_type = ContentType.objects.get_for_model(Post)
    obj_id = Post.id
    comments = Comment.objects.filter(content_type=content_type, object_id=obj_id)
    context = {
        "title": instance.title,
        "instance": instance,
        "comments": comments,
    }
    return render(request, "post_detail.html", context)
  

到目前为止,我已经尝试过使用这种方法使它基于我知道是错误的类。

class PostDetailView(LoginRequiredMixin,DetailView):
    model = Post
    template_name = 'posts/post_detail.html'
    content_type = ContentType.objects.get_for_model(Post)
    obj_id = Post.id
    comments = Comment.objects.filter(content_type=content_type, object_id=obj_id)

但这给我这样的错误

return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute'

1 个答案:

答案 0 :(得分:1)

函数视图中也存在问题。查看基于类的视图,如果您想在详细信息视图中显示注释,那么您就不需要这些了,

class PostDetailView(DetailView):
    model = Post
    template_name = 'posts/post_detail.html'

要显示与帖子相关的评论,您需要使用相关名称,在评论模型中,您应该这样命名,

class Comment(models.Model):
     post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='postcomments')
     # ... (other code)

要以html形式显示,您需要做的所有事情

{% for comment in post.postcomments.all %}
    {{comment.text}}  #add according to your model
{% endfor %}

要在同一页面中创建评论,您需要添加一些其他内容,请确保您也具有评论表。

 class PostDetailView(DetailView):
     model = Post
     template_name = 'post/post_detail.html'

     def get_context_data(self, **kwargs):
         context = super(PostDetailView, self).get_context_data(**kwargs)
         context['commentform'] = CommentForm()
         return context

     def post(self, request, pk):
         post = get_object_or_404(Post, pk=pk) #Assuming you have <int:pk> in url, if you have slug change pk to slug
         form = CommentForm(request.POST) #Add your comment form

         if form.is_valid():
            obj  = form.save(commit=False)
            obj.post = post  
            obj.user = self.request.user
            obj.save()
            return redirect('detail', post.pk) # Correct it according your urlpattern name

在相同的帖子详细信息html中,您可以简单地添加与在其他表单模板中使用的html相同的

<form method="POST" action="" >
  {% csrf_token %}
  <p> {{form}}  </p>
  <button type="submit"> Create </button>
</form>