I have a TextField(text area) form on my page where users can submit comments and have them displayed.
I've left several comments and none of them is showing up. I can see everytime i add one the space where the comments are supposed to be grows, after inspecting the page with the dev tools, there's just a bunch of empty HTML tags for all the comments i left, cant figure what the issue is
models.py:
class Comments(models.Model):
comment = models.TextField(max_length=250)
user_commented = models.CharField(max_length=64)
list_title = models.CharField(max_length=64)
list_author = models.CharField(max_length=64)
date_time = models.DateTimeField(default=timezone.now, blank=True)
def __str__(self):
return f"{self.user_commented}, {self.date_time}, {self.comment}"
forms.py
class CommentForm(ModelForm):
class Meta:
model = Comments
fields = ['comment']
views.py
commentform = CommentForm()
comment = CommentForm(request.POST)
if "comment" in request.POST:
if comment.is_valid:
comment_data = Comments.objects.create(list_title=title, user_commented=username, list_author=author, comment=comment)
comment_data.save()
comment_data = list(Comments.objects.all().filter(list_title=title))
return render(request, "auctions/listing.html", {
"form": form,
"listing": listing_object,
"checkbox": checkbox,
"commentform": commentform,
"max_bid": max_bid,
"comments": comment_data
})
template
<form action="{% url 'listing' listing.title %}" method="POST">
{% csrf_token %}
{{ commentform }}
<input type="submit" value="Comment" name="comment">
</form>
<div >
<h5>Comments</h5>
{% for comment in comments %}
<p>{{ comments.user_commented }}</p><span>{{ comments.date_time }}</span>
<p>{{ comments.comment }}</p>
<br>
{% endfor %}
</div>
GET request: I grabbed all the comments from the database into a variable before passing it to the GET request like so
comment_data = list(Comments.objects.all().filter(list_title=title))
return render(request, "auctions/listing.html", {
"form": form,
"listing": listing_object,
"checkbox": checkbox,
"commentform": commentform,
"max_bid": max_bid,
"users": author,
"comments": comment_data
})
CodePudding user response:
You did wrong here:
{% for comment in comments %}
<p>{{ comment.user_commented }}</p><span>{{ comment.date_time }}</span>
<p>{{ comment.comment }}</p> #You had added comments here instead of comment
<br>
{% endfor %}
According to for loop, you had added comments instead of comment.