Django: 视图“未返回 HttpResponse 对象”
我在提交表单时收到了一个错误,提示我没有返回一个httpresponse对象,我有点搞不懂为什么会这样:
Exception Type: ValueError at /contact/addcontact
Exception Value: The view openshift.contactapplication.views.contact didn't return an HttpResponse object.
这是我的视图代码:
# Create your views here.
from django.shortcuts import render_to_response, render
from django.http import HttpResponseRedirect, HttpResponse
#forms imports
from contactapplication.forms import applicantsForm
#model imports
from contactapplication.models import applicantsModel
def contact(request):
if request.method == 'POST':
form = applicantsForm(request.POST)
if form.is_valid():
clean_form =form.cleaned_data
collect = applicantsModel(first_name=clean_form['first_name'], last_name=clean_form['last_name'],
linkedin_profile=clean_form['linkedin_profile'], elevator_pitch=clean_form['elevator_pitch'],
email=clean_form['email'], phone=clean_form['phone'])
collect.save()
return HttpResponseRedirect('contactUs/contactUs.html') #the same page, change to thankyou page later
else:
return render(request, 'contactUs/contactUs.html',)
问题可能出在哪里呢?我明明是返回了一个 HttpResponseRedirect
对象啊。
1 个回答
7
当请求方式是 POST 并且表单有效时,你会返回一个 HttpResponseRedirect
,这表示重定向到另一个页面。如果请求方式不是 POST,你就返回 render()
的结果,这个结果是一个 HttpResponse。到这里为止,一切都很好。
但是,如果请求方式是 POST 而表单无效,那么你就没有明确返回任何东西(这时候会返回 None
)。
我假设我理解了缩进的部分——在你的问题中,缩进有点问题,比如 def
下面的代码没有缩进。