首页 > 解决方案 > 如何扩展基于类的视图

问题描述

我已经创建了显示帖子内容的基于类的视图。我还添加了在那里发表评论的能力,但是评论表单不起作用。

视图.py

class PostDetailView(DetailView):
    model=Post
    template_name='blogdetail.html'
    pk_url_kwarg='id'
   


    def comments(request):
        comments=post.comments.all()
        new_comment=None
        if request.method=="POST":
            comment_form=CommentForm(data=request.POST)
            if comment_form.is_valid():
                new_comment=comment_form.save(committ=False)
                new_comment.post=post
                new_comment.save()
        else:
            comment_form=CommentForm()
        return render(request, 'allblogs.html', {'comments':comments, 'comment_form':comment_form,
        'new_comment':new_comment})
   

表格.py

class CommentForm(forms.ModelForm):
    class Meta:
        model=Comment
        fields=['post','body']

blogdetail.html

{% extends 'base.html' %}

{% block content %}
<h1>{{post.title}}</h1>
<p>{{post.created_on}}</p>
<p><a href="{% url 'userpage' post.author.username %}"></a>:{{post.author}}</p>
<p>{{post.text}}</p>
<form>
{{comment_form.as_p}}
<p><input type="submit" value="add"></p>
{% csrf_token %}
</form>

{% endblock content %}

标签: pythondjango

解决方案


类基础视图不能以这种方式工作。如果您查看您的课程,您没有调用您的评论功能。我建议你看看这个页面。除此之外,为了为您的作者创建 URL,我建议您在模型中使用get_absolute_url并在模板中使用它,如下所示:{{ author.get_absolute_url }}

希望这个答案对你有所帮助。


推荐阅读