python - 我的评论没有显示在 HTML 页面上
问题描述
嘿伙计们,我正在建立一个拍卖网站,由于某种原因,我的评论(一个名为 commentQuery 的字典)没有显示在 HTML 页面上。
有人知道为什么吗?我敢肯定这是我遗漏的小事。
谢谢!相关代码如下:
视图.py:
def comment(request):
username = request.POST.get("username")
itemID = request.POST.get("itemID")
comment = request.POST.get("comment")
new = Comment.objects.create(username = username, comment = comment, itemID = itemID)
new.save()
commentQuery = Comment.objects.all()
return render(request, "auctions/post.html", { "commentQuery": commentQueries})
post.html:
<form name="comment"
action="/comment"
method="post">
{% csrf_token %}
<h2>Comments</h2>
{% if user.is_authenticated %}
<input autofocus class="form-control" type="text" name="comment" placeholder="Enter Comment">
<input autofocus class="form-control" type="hidden" name="itemID" value={{p.title}}{{p.price}}>
<input autofocus class="form-control" type="hidden" name="username" value={{user.username}}>
<input class="btn btn-primary" type="submit" value="Add Comment">
{% endif %}
</form>
{% for commentQuery in commentQueries %}
<li>{{ commentQuery.comment }} by {{ commentQueries.username }}</li>
{% endfor %}
{% endblock %}
解决方案
您将 传递commentQueries
给 name 下的模板commentQuery
,因此如果您编写,那将不起作用。您应该将其传递为,或者更方便:{% for commentQuery in commentQueries %}
commentQueries
comments
def comment(request):
username = request.POST.get('username')
itemID = request.POST.get('itemID')
comment = request.POST.get('comment')
Comment.objects.create(
username=username,
comment=comment,
itemID=itemID
)
comments = Comment.objects.all()
return render(request, 'auctions/post.html', { 'comments': comments})
然后,您可以在模板中呈现评论:
{% for comment in comments %}
<li>{{ comment.comment }} by {{ comment.username }}</li>
{% endfor %}
然而,最好将ForeignKey
[Django-doc]用于用户模型,而不是存储用户名。例如,如果您复制了用户名,然后用户更改了他们的用户名,则您将无法再检索有关该用户的用户数据。
注意:如果 POST 请求成功,您应该制作一个
redirect
[Django-doc] 来实现Post/Redirect/Get模式 [wiki]。这样可以避免在用户刷新浏览器时发出相同的 POST 请求。
推荐阅读
- c - 在 if 条件内打印 char 的问题
- python - 等效于“kubectl wait --for”命令的 Kubernetes python 客户端
- android - 在 Android 上使用 requestNetwork 后如何恢复 Wi-Fi 连接
- python - 导入 csv 文件时列表索引超出范围
- linux - 为什么我的 Postgres 数据库工作了一段时间,然后重新启动后无法“启动服务器”?
- javascript - Google Apps 脚本 - 根据多个条件返回数据结果
- python - 时钟上的绘图线
- sql-server - 我的 sql server 没有维护计划向导
- javascript - 如何获得电子商务网站中订购商品的运费
- swift - Swiftui coredata foreach 滚动视图:删除按钮