首页 > 解决方案 > 我的评论没有显示在 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 %}

标签: pythondjango

解决方案


您将 传递commentQueries给 name 下的模板commentQuery,因此如果您编写,那将不起作用。您应该将其传递为,或者更方便:{% for commentQuery in commentQueries %}commentQueriescomments

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 请求。


推荐阅读