如何处理httpresponseredirect

时间:2017-12-13 12:09:06

标签: python django

TEST2 / urls.py

from django.conf.urls import url
from .import views
from .forms import  forms

urlpatterns=[
    url(r'^$',views.index,name='index'),
    url(r'^thankyou/$',views.thankyou,name='thankyou')
]

TEST1 / urls.py

from django.contrib import admin
    from django.conf.urls import url , include

    urlpatterns = [
        url(r'^admin/', admin.site.urls),
        url(r'^test2/',include('test2.urls')),
    ]

views.py   这个视图应该重定向到/ test2 / thankyou /但是它为什么要/ thankyou 以及如何启用重定向方法

给出的视图
from django.shortcuts import render
    from django.http import HttpResponseRedirect,HttpResponse
    from .forms import Get_name

    # Create your views here.
    def index(request):
        if request.method == 'POST':
            form = Get_name(request.POST)
            if form.is_valid():
                return HttpResponseRedirect('/thankyou/')
        else:
            form = Get_name()
        return render(request, 'test2/name.html' , {'form':form})

    def thankyou(request):
        return HttpResponse('sai chaitanya')

name.html 在提交表单后,它应该重定向到test2 / thankyou,但它会转到/ thankyou。

<form action="/thankyou/" method="post">
        {% csrf_token %}
        {{ form.as_p }}
        <input type="submit" value="Submit" />
    </form>

forms.py

from django import forms
user_choice =[('space',''),('passenger','Passenger'),('driver','Driver')]

class Get_name(forms.Form):
    user_name = forms.CharField(label='user name',max_length='50',required=True)
    pass_word1 = forms.CharField(widget=forms.PasswordInput,max_length='20',label='Password')
    pass_word2 = forms.CharField(widget=forms.PasswordInput, max_length='20', label='Confirm Password')
    email = forms.EmailField(label='email',max_length='100')
    mobile = forms.CharField(label='contact number ',widget=forms.NumberInput,max_length='10')
    address = forms.CharField(label='Address',max_length='100')
    user_type = forms.CharField(label='select user type',widget=forms.Select(choices=user_choice))

1 个答案:

答案 0 :(得分:2)

它会转到/thankyou/,因为您已对网址/thankyou/进行了硬编码:

 return HttpResponseRedirect('/thankyou/')

您可以通过将代码更改为:

重定向到/test2/thankyou/
 return HttpResponseRedirect('/test2/thankyou/')

但最佳做法是撤消网址而不是硬编码:

from django.urls import reverse

return HttpResponseRedirect(reverse('thankyou'))

可以使用redirect快捷方式简化:

from django.shortcuts import redirect

return redirect('thankyou')