Django HttpResponseRedirect [英] Django HttpResponseRedirect

查看:131
本文介绍了Django HttpResponseRedirect的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个基本的联系表单,当用户提交信息时,它应该重定向到谢谢页面。

I have created a basic contact form, and when the user submits information, it should redirect to the Thank You page.

这是我在views.py文件:

This is the code I have in the views.py file:

def contact(request):
    # if no errors...
        return HttpResponseRedirect('/thanks/')

这是我在url中的urlpatterns中有的。 py文件:

This is what I have in the urlpatterns in the urls.py file:

(r'^contact/$', contact),
(r'^contact/thanks/$', contact_thanks),

这两个页​​面都使用硬编码的URL。但是,当我将表单/ contact / it重定向到/ contact(无结束斜杠)时,这是一个不存在的页面(404或错误页面告诉我我需要一个斜线)。什么原因是不正确的重定向,我该如何解决这个问题?谢谢。

Both pages work at the hard-coded URL. However, when I submit the form on /contact/ it redirects to /contact (no ending slash), which is a non-existant page (either a 404 or an error page telling me I need a slash). What is the reason it not correctly redirecting, and how can I fix this? Thank you.

更新:返回HttpResponseRedirect('/ contact / thanks /')是我现在拥有的,但问题是提交按钮(使用POST)不重定向到URL - 它根本不重定向。

UPDATE: the return HttpResponseRedirect('/contact/thanks/') is what I now have, but the problem is that the submit button (using POST) does not redirect to the URL -- it doesn't redirect at all.

推荐答案

这不是POST按钮应该重定向,而是视图

It's not the POST button that should redirect, but the view.

如果没有指定格式(我的意思是HTML表单标签)POST到同一个URL。如果表单在/ contact /上,则POST / on / contact /(带或不带斜杠,这是相同的)。

If not differently specified the form (i mean the HTML form tag) POSTs to the same URL. If the form is on /contact/, it POSTs on /contact/ (with or without slash, it's the same).

在视图中,您应该重定向到谢谢。从文档:

It's in the view that you should redirect to thanks. From the doc:

def contact(request):
    if request.method == 'POST': # If the form has been submitted...
        form = ContactForm(request.POST) # A form bound to the POST data
        if form.is_valid(): # All validation rules pass
            # Process the data in form.cleaned_data
            # ...
            return HttpResponseRedirect('/thanks/') # Redirect after POST
    else:
        form = ContactForm() # An unbound form

    return render_to_response('contact.html', {
        'form': form,
    })

更改/谢谢/与/联系/谢谢/完成。

Change /thanks/ with /contact/thanks/ and you're done.

这篇关于Django HttpResponseRedirect的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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