如何在django的博客文章中标记评论?

时间:2018-12-03 07:40:19

标签: python django

我是django的新手,目前正在开发博客。

我正在尝试使用CreateView模板为查看者插入评论表单。观众将需要登录以输入他们的评论。他们的用户名将被标记到相应博客的评论中,而无需指示任何内容。没有错误,但数据未按预期存储。评论被接受,但未出现在博客上。去检查django管理,那里显然只存储了作者,而没有存储评论所在的博客文章。下面是我的代码,存储在(views.py)中。

class CommentCreate(LoginRequiredMixin,CreateView):
    model = Comment
    fields = ['comment','blog']
    template_name = 'catalog/blog_comment.html'

    def get_context_data(self, **kwargs):
        context = super(CommentCreate, self).get_context_data(**kwargs)
        context['blog'] = get_object_or_404(Blog, pk = self.kwargs['pk'])
        return context

    def form_valid(self, form):
        form.instance.author = self.request.user
        return super(CommentCreate, self).form_valid(form)

    def get_success_url(self): 
        return reverse('blog-detail', kwargs={'pk': self.kwargs['pk'],})

模型Blog和Comment在下面的单独文件(models.py)中定义

class Blog(models.Model):
    title = models.CharField(max_length=200)    
    blogger = models.ForeignKey('Blogger', on_delete=models.SET_NULL, 
null=True)  
    content = models.TextField(max_length=1000, help_text='Write some stuffs 
for your blog')
    post_date = models.DateField(default=date.today)

    class Meta:
        ordering = ['post_date',"title","blogger"]

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('blog-detail', args=[str(self.id)])


class Comment(models.Model):
    comment = models.TextField(max_length=1000, help_text='Comment on the 
 blog')
    author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    blog = models.ForeignKey("Blog", on_delete=models.SET_NULL, null=True)
    post_date = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-post_date']

    def __str__(self):
        return self.comment

任何建议都值得赞赏。谢谢。

1 个答案:

答案 0 :(得分:0)

问题已解决。原来我忘了将数据保存在form_valid中。 附加的代码如下所示。

class CommentCreate(LoginRequiredMixin,CreateView):
    model = Comment
    fields = ['comment','blog']
    template_name = 'catalog/blog_comment.html'

    def get_context_data(self, **kwargs):
        context = super(CommentCreate, self).get_context_data(**kwargs)
        context['blog'] = get_object_or_404(Blog, pk = self.kwargs['pk'])
        return context

    def form_valid(self, form):
        form.instance.author = self.request.user
        form.instance.blog = get_object_or_404(Blog, pk = self.kwargs['pk'])
        return super(CommentCreate, self).form_valid(form)