我想知道是否有人知道:
例如,我有一个用户填写的表单,当他提交时,页面将重定向到“谢谢”页面。一切正常。在 urls.py 我有这一行指出该页面存在:
url(r'^thankyou/$', 'render_form'),
但是,当我输入 url mysite.com/thankyou/ 时,会出现“谢谢”页面......但我需要它仅在我提交表单时出现并在用户尝试直接打开它时隐藏它。
请帮忙。提前致谢!
您可以在重定向之前在表单处理视图中的会话中放置一些内容,并在感谢 URL 中检查它:如果它不存在,则返回 403 错误。就像是:
def form_handling_view(request):
if request.POST:
form = MyForm(request.POST)
if form.is_valid():
... handle the form ...
request.session['form_posted'] = True
return redirect('thank_you')
def thank_you(request):
if not request.session.pop('form_posted', False):
return HttpResponseForbidden('not permitted')
... render thank_you page ...
注意我pop
在thank_you中使用以确保无论如何都从会话中删除密钥。