Django在刷新页面时自动重新提交表单

vyswwuz2  于 2023-08-08  发布在  Go
关注(0)|答案(2)|浏览(158)

每当我填写表格,然后我点击提交按钮的形式存储在数据库中,它存储的数据完美,但当我刷新页面,它再次提交。所以问题是它在数据库中多次显示相同的数据。

这是我的Django模板代码

<h4 class="text-center alert alert-success">Add New Students</h4>
    <form action="" method="POST">
      {% csrf_token %} 
      {{form.as_p}}
      <input type="Submit" class="btn btn-success" value="Add">

字符串
我该如何应对?

这里是我的视图函数

def add_show(request):
    if request.method == 'POST':
        fm = StudentRegistration(request.POST)
        if fm.is_valid():
            nm = fm.cleaned_data['name']
            em = fm.cleaned_data['email']
            pw = fm.cleaned_data['password']
            reg = User(name=nm, email=em, password=pw)
            reg.save()
            fm = StudentRegistration()
    else:
      fm = StudentRegistration()
    stud = User.objects.all()

    return render(request, 'enroll/addandshow.html', {'form': fm, 'stu':stud})

wtzytmuj

wtzytmuj1#

试着用正确的方式使用Post方法。

rslzwgfq

rslzwgfq2#

因此,Post方法应妥善处理。在Post方法之后,你应该使用redirect(到同一个视图)而不是render

def add_show(request):
        if request.method == 'POST':
            fm = StudentRegistration(request.POST)
            if fm.is_valid():
                nm = fm.cleaned_data['name']
                em = fm.cleaned_data['email']
                pw = fm.cleaned_data['password']
                reg = User(name=nm, email=em, password=pw)
                reg.save()
                fm = StudentRegistration()
                return redirect('url_mapped_to_current_view') 
        else:
          fm = StudentRegistration()
        stud = User.objects.all()
    
        return render(request, 'enroll/addandshow.html', {'form': fm, 'stu':stud})

字符串

相关问题