在POST后重定向并传递数据时,重定向URL的持久性

时间:2015-05-07 22:49:48

标签: django django-forms http-post http-redirect

成功提交表单后,我会重定向到“成功”页面,该页面会显示“谢谢”消息以及有关提交的一些信息。为此,我将POST数据放入会话,重定向到相应的URL,然后使用会话数据呈现模板。

但是,这意味着如果有人手动导航到“成功”网址,他们就会看到之前表单提交中的“成功”消息。我该如何预防呢?表单在/register/处理。成功提交的内容将重定向至/register/success。我希望在浏览器中物理输入/register/success/的人(没有提交表单)来查看错误页面或其他内容。怎么办呢?

urls.py

url(r'^register/$', views.register, name='register'),
url(r'^register/success/$', views.registration_success, name='registration_success'), 

views.py

def register(request):
    if request.method == 'POST':
        if the_form.is_valid():
            my_id = the_form.cleaned_data['myid']
            email_addr = the_form.cleanedJ_data['emailaddr']
            request.session['registration'] = {'my_id': my_id, 'email_addr': email_addr }

            return HttpResponseRedirect(reverse('polls:registration_success'))


def registration_success(request):
    template = loader.get_template('polls/submitted.html')
    context = RequestContext(request, request.session.get('registration'))
    return HttpResponse(template.render(context))

1 个答案:

答案 0 :(得分:0)

您可以使用Django会话来实现它。这是使用您的代码的示例。

def register(request):
    if request.method == 'POST':
        if the_form.is_valid():
            my_id = the_form.cleaned_data['myid']
            email_addr = the_form.cleanedJ_data['emailaddr']
            request.session['registration'] = {'my_id': my_id, 'email_addr': email_addr }
            request.session['form-submitted'] = True
            return HttpResponseRedirect(reverse('polls:registration_success'))


def registration_success(request):
    if not request.session.get('form-submitted', False):
        # handle the case where there is no form submitted
        return HttpResponseRedirect(reverse('polls:register'))
    template = loader.get_template('polls/submitted.html')
    context = RequestContext(request, request.session.get('registration'))
    return HttpResponse(template.render(context))