[英]How to add comment form in ListView Django?
進入:我在 listviewpage 中有一個包含多個帖子的查詢集。 我想在listviewpage
而不是detailpageview
中為每個帖子添加評論表單。 我還在帖子列表的 forloop 中包含 html 表格
問題:下面的代碼出現錯誤'ValidationError' object has no attribute 'get'
如果有任何幫助,我將不勝感激。
模型.py
class Comment(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
post = models.ForeignKey(Post, on_delete=models.CASCADE, null=True, blank=True)
comments = models.TextField(max_length=1000, blank=True)
created_at = models.DateTimeField(auto_now_add=True)
視圖.py
def ListViewPage(request):
queryset = Post.objects.all()
comment = CommentForm(data=request.POST)
if request.method == 'POST':
try:
pk = request.POST.get('pk')
post = Post.objects.get(id=pk)
except Post.DoesNotExist:
return ValidationError(f'No Post by id {pk}')
if comment.is_valid():
com = comment.save(commit=False)
com.posts = post
com.save()
context = {
'posts': queryset,
'form': comment
}
return render(request, 'post_list.html', context)
post_list.html
{% for object in sales %}
<div class="hpanel hblue">
<div class="row">
<div class="col-sm-3">
<div class="project-label">Saler</div>
<small>{{ object.user }}</small>
</div>
<div class="col-sm-4">
<div class="project-label">Timestamp</div>
<small>{{ object.created_on|naturalday }}</small>
</div>
<div class="col-sm-4">
<div class="project-label">Product</div>
<small>{{ object.created_on|naturalday }}</small>
</div>
</div>
<form action="." method="POST"> {% csrf_token %}
<div class="form-group">
<textarea name="comments" id="id_comments" cols="30" rows="2" required class="form-control"
placeholder="comments..."></textarea>
</div>
<button type="submit" class="btn btn-sm btn-default">submit</button>
</form>
</div>
{% endfor %}
您不能在視圖中返回 aq ValidationError
,您需要返回 HTTP 響應,或者引發Http404
異常,例如:
from django.http import Http404
from django.shortcuts import redirect
def ListViewPage(request):
queryset = Post.objects.all()
if request.method == 'POST':
try:
pk = request.POST.get('pk')
post = Post.objects.get(id=pk)
except Post.DoesNotExist:
raise Http404(f'No Post by id {pk}')
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
comment_form.instance.posts = post
comment_form.save()
return redirect('')
else:
comment_form = CommentForm()
context = {
'posts': queryset,
'form': comment_form
}
return render(request, 'post_list.html', context)
注意:如果 POST 請求成功,您應該進行
redirect
[Django-doc]以實現Post/Redirect/Get模式 [wiki] 。 這樣可以避免在用戶刷新瀏覽器時發出相同的 POST 請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.