【问题标题】:Django clear form field after a submit form. form create in forms.py提交表单后,Django 清除表单字段。在 forms.py 中创建表单
【发布时间】:2020-10-25 05:41:48
【问题描述】:

我尝试了很多但找不到解决方案 我也尝试了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>

  

【问题讨论】:

  • 函数似乎没有正确缩进。此外,我并不完全清楚你的目标是什么。
  • 您能否详细说明您正在尝试什么以及出了什么问题
  • 当用户点击提交按钮然后清除表单域
  • 提交表单后表单域不为空
  • @WillemVanOnsem 谢谢人

标签: javascript django django-forms django-templates django-formtools


【解决方案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)

【讨论】:

    猜你喜欢
    • 2014-10-17
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    • 2015-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多