进入:我在listviewpage中查询了多篇文章。我想在listviewpage
而不是detailpageview
中添加每个帖子的评论表单。我还将html表单包含在帖子的forloop列表中
问题:下面的代码出现错误'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
异常,例如:相关问题 更多 >
编程相关推荐