如何在ListView Django中添加注释表单?

2024-09-30 16:35:29 发布

您现在位置:Python中文网/ 问答频道 /正文

进入:我在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 %}

Tags: divformtrueobjectonmodelsrequestcomment
1条回答
网友
1楼 · 发布于 2024-09-30 16:35:29

您可以返回aqValidationError。在视图中,您需要返回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('name-of-some-view')
    else:
        comment_form = CommentForm()
    context = {
        'posts': queryset,
        'form': comment_form
    }
    return render(request, 'post_list.html', context)

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.

相关问题 更多 >