您好我正在处理一个简单的表单。表单提交正常但如果我刷新页面则重新提交数据。似乎表单在提交后持有数据,我假设自提交后请求方法发布。问题是提交清除Django表单后的最佳方法。提交后,表单变量不应再保留值。感谢
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))
答案 0 :(得分:1)
使用reverse而不是render to response
if form.is_valid():
nameIn = form.cleaned_data['name']
reviewIn = form.cleaned_data['review']
newReview = Reviews(name = nameIn, review = reviewIn)
newReview.save()
return HttpResponseRedirect(reverse('app_name:url'))
答案 1 :(得分:1)
通常,您会在处理表单/ POST请求后发出重定向(这是常见的Web开发实践,以避免您提到的重新提交问题)。因此,您可以像render_to_response
一样发布HttpResponseRedirect
而不是if form.is_valid():
# Process form as desired here
# Simple example; use reverse() to avoid hard-coding URLs
return HttpResponseRedirect('/success/')
:
{{1}}
查看using a form in view以获取通常如何处理表单的框架。
答案 2 :(得分:0)
您还可以使用“重定向”快捷方式:
from django.shortcuts import redirect
...
return redirect(newReview)
这假设您在评论模型中定义了get_absolute_url。
有关详细信息,请参阅the docs。