python - 如何扩展基于类的视图
问题描述
我已经创建了显示帖子内容的基于类的视图。我还添加了在那里发表评论的能力,但是评论表单不起作用。
视图.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 %}
解决方案
类基础视图不能以这种方式工作。如果您查看您的课程,您没有调用您的评论功能。我建议你看看这个页面。除此之外,为了为您的作者创建 URL,我建议您在模型中使用get_absolute_url并在模板中使用它,如下所示:{{ author.get_absolute_url }}
希望这个答案对你有所帮助。
推荐阅读
- jquery - Django Ajax 表单未提交和页面冻结
- c# - 如何在将特定数据插入 SQL 数据库表之前检查文本文件中是否存在特定数据?
- python - Python 正则表达式在列表中仅找到一项而不是全部
- python - 如何使用 PyQt5 编辑 PlotWidget 的样式参数
- angular - 将 npm 包添加到 Angular 库
- python - 在 S3 中 create_export_task 之后以 .gz 格式读取 CloudWatch 日志时出现问题
- mapbox - 带有自定义标记和折线的 Mapbox 静态图像
- python - 用python抓取时收不到数据怎么办?
- javascript - 更改 server.js 文件以使用 heroku 将 socket.io 导出到 Web
- c# - 从一个控制器到另一个控制器的 RedirectToAction