Django 在提交表单后清除表单字段。在 forms.py 中创建表单

Django clear form field after a submit form. form create in forms.py

我尝试了很多但找不到解决方案 我也尝试 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() Only the field shows blank But the data is submitted when we refresh

HTML 文件

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

  

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

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