1

我尝试了很多但找不到解决方案 我也尝试了 javascript 但找不到解决方案

def postPage(request, id):
    post = Post.objects.get(pk=id)
    showcomment = Comment.objects.filter(postby = id)
    form = commentForm()
    form = commentForm(request.POST)
    form.instance.postby = post   
    if form.is_valid():
       form.save()
       form = commentForm()
       redirect('postpage', id=post.sno)
       context = {'post':post, 'form':form, 'showcomment':showcomment}
       return render(request, 'blog/postpage.html', context)

form = commentForm() 只有字段显示空白 但是我们刷新时提交数据

HTML 文件

form action="." method="POST">
{{form}}
{% csrf_token %}
<input type="submit">
</form>

  
4

1 回答 1

1

form您可以在呈现表单之前立即创建一个新的。但是请注意,通过创建新表单,错误将会消失。此外,对于不是那么小的表单,通常希望行为返回(部分)填写的表单,以便用户可以继续编辑:

def postPage(request, id):
    if request.method == 'POST':
        form = commentForm(request.POST)
        if form.is_valid():
            form.instance.postby_id = id
            form.save()
            redirect('postpage', id=post.sno)
   form = commentForm()
   showcomment = Comment.objects.filter(postby=id)
   context = {'post': post, 'form': form, 'showcomment': showcomment}
   return render(request, 'blog/postpage.html', context)
于 2020-07-04T19:23:26.993 回答