Django“视图没有返回 HttpResponse 对象。”
我有一个简单的视图,在其中保存表单。代码看起来“干净”,但我无法摆脱错误:
“视图没有返回 HttpResponse 对象。”
虽然我在网上搜索过,但没有找到相关的说明。
def classroom_privacy(request,classname):
theclass = Classroom.objects.get(classname=classname)
if request.method == 'POST':
form = PrivacyClass(request.POST)
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.save()
return HttpResponseRedirect('.')
else:
form = PrivacyClass()
return render_to_response('classroom/classroom_privacy.html', {'form': form},
context_instance=RequestContext(request))
I have a simple view in which I'm saving a form. The code seems 'clean', but I can't get rid of the error:
"The view didn't return an HttpResponse object."
Though I've searched on the web, I did not find a relevant indication.
def classroom_privacy(request,classname):
theclass = Classroom.objects.get(classname=classname)
if request.method == 'POST':
form = PrivacyClass(request.POST)
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.save()
return HttpResponseRedirect('.')
else:
form = PrivacyClass()
return render_to_response('classroom/classroom_privacy.html', {'form': form},
context_instance=RequestContext(request))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您使用Django Rest框架。使用以下代码返回HTTP 响应来解决此问题。
JSON响应返回示例:
有关HttpResponse的更多详细信息:
https://docs.djangoproject.com/en /3.1/ref/request-response/#django.http.HttpResponse
If you are using the Django Rest framework. Use the below code to return the HTTP response to resolve this issue.
JSON Response return example:
For more details about HttpResponse:
https://docs.djangoproject.com/en/3.1/ref/request-response/#django.http.HttpResponse
验证代码的缩进
如果是 get 请求,则
;如果是 post 请求,则渲染未绑定的表单;如果是 post 请求,则渲染无效的表单;如果是 post 请求,则渲染绑定的表单;
如果是有效的表单,则重定向页面
verify the indentation of your code
if it is get request, render a unbound form
if it is post request and invalid form render a bound form
if it is post request and valid form redirect the page
所有视图函数都必须返回某种 HttpResponse 对象。您的函数中存在一个代码路径,将返回
None
。当request.method != 'POST'
时就会发生这种情况,并且您将简单地“从函数的末尾掉下来”(将返回None
)。All view functions must return some kind of HttpResponse object. There exists a code path in your function where
None
will be returned instead. This will occur whenrequest.method != 'POST'
and you'll simply "fall off the end" of your function (which will returnNone
).