Reputation: 143
Hey guys I'm building an auction site and for some reason my comments (a dict called commentQuery) is not displaying on the HTML page.
Anyone see why? I'm sure it's something minor I'm missing.
Thanks! relevant code below:
views.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 %}
Upvotes: 1
Views: 63
Reputation: 476574
You passed the commentQueries
to the template under the name commentQuery
, hence if you write {% for commentQuery in commentQueries %}
, that will not work. You should pass it as commentQueries
, or perhaps more convenient 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})
In the template you can then render the comments:
{% for comment in comments %}
<li>{{ comment.comment }} by {{ comment.username }}</li>
{% endfor %}
It might however be better to work with a ForeignKey
[Django-doc] to the user model, and not to store the username. If you copy the username, and later the user changes their username, you can no longer retrieve user data about that user for example.
Note: In case of a successful POST request, you should make a
redirect
[Django-doc] to implement the Post/Redirect/Get pattern [wiki]. This avoids that you make the same POST request when the user refreshes the browser.
Upvotes: 1