Django表单刷新后再次提交 [英] Django form submit again on refresh

查看:325
本文介绍了Django表单刷新后再次提交的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在编写一个简单的表格.表单可以很好地提交,但是如果刷新页面,它将重新提交数据.似乎表单提交后保存数据,我假设因为提交后请求方法是post.问题是提交后在Django中清除表单的最佳方法是什么.提交后,表单变量不应再包含这些值.谢谢

Hello I am working on a simple form. The form submits fine but if I refresh the page it resubmits the data. Seems the form is holding the data after submit and I assume since after the submit the request method is post. Question is what is the best way after the submit to clear the form in Django. After the submit the form variables should not be holding the values anymore. Thanks

def testimonials(request, template_name="testimonials.html"):
reviews = Reviews.objects.all()
if request.method == 'POST':
    form = forms.ReviewsForm(data = request.POST)
    # create a new item

    if form.is_valid(): # All validation rules pass
        # Process the data in form.cleaned_data
        # ...
        if form.is_valid():
            nameIn = form.cleaned_data['name']
            reviewIn = form.cleaned_data['review']
            newReview = Reviews(name = nameIn, review = reviewIn)
            newReview.save()
            return render_to_response(template_name, locals(), context_instance=RequestContext(request))

else:
    # This the the first page load, display a blank form
    form = forms.ReviewsForm()

    return render_to_response(template_name, locals(), context_instance=RequestContext(request))

推荐答案

通常,您将在处理表单/POST请求后发出重定向(这是常见的Web开发实践,可以避免您提到的重新提交问题).因此,您可以像这样发出HttpResponseRedirect代替render_to_response:

Typically, you would issue a redirect after processing a form/POST request (this is common web development practice to avoid the resubmission issue you mentioned). So instead of a render_to_response, you might issue a HttpResponseRedirect like so:

if form.is_valid(): 
        # Process form as desired here
        # Simple example; use reverse() to avoid hard-coding URLs
        return HttpResponseRedirect('/success/')

使用使用视图中的表单,了解表单通常的处理方式.

Check out the using a form in view for a skeleton of how forms are typically processed.

这篇关于Django表单刷新后再次提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆