Python 该视图未返回 HttpResponse 对象。它返回 None 代替

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26258905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:16:44  来源:igfitidea点击:

The view didn't return an HttpResponse object. It returned None instead

pythondjangodjango-views

提问by aliteralmind

I have the following simple view. Why is it resulting in this error?

我有以下简单的看法。为什么会导致这个错误?

The view auth_lifecycle.views.user_profile didn't return an HttpResponse object. It returned None instead.

The view auth_lifecycle.views.user_profile didn't return an HttpResponse object. It returned None instead.

"""Renders web pages for the user-authentication-lifecycle project."""
from django.shortcuts               import render
from django.template                import RequestContext
from django.contrib.auth            import authenticate, login

def user_profile(request):
    """Displays information unique to the logged-in user."""

    user = authenticate(username='superuserusername', password='sueruserpassword')
    login(request, user)

    render(request, 'auth_lifecycle/user_profile.html',
           context_instance=RequestContext(request))

采纳答案by aliteralmind

Because the view must returnrender, not just call it. Change the last line to

因为视图必须返回render,而不仅仅是调用它。将最后一行更改为

return render(request, 'auth_lifecycle/user_profile.html',
           context_instance=RequestContext(request))

回答by Angie Alejo

I had the same error using an UpdateView

我在使用 UpdateView 时遇到了同样的错误

I had this:

我有这个:

if form.is_valid() and form2.is_valid():
    form.save()
    form2.save()
    return HttpResponseRedirect(self.get_success_url())

and I solved just doing:

我解决了只做:

if form.is_valid() and form2.is_valid():
    form.save()
    form2.save()
    return HttpResponseRedirect(reverse_lazy('adopcion:solicitud_listar'))

回答by Ravi Teja Mureboina

if qs.count()==1:
        print('cart id exists')
        if ....

else:    
        return render(request,"carts/home.html",{})

Such type of code will also return you the same error this is because of the intents as the return statement should be for else not for if statement.

这种类型的代码也会向您返回相同的错误,这是因为 return 语句应该用于 else 而不是用于 if 语句的意图。

above code can be changed to

上面的代码可以改成

if qs.count()==1:
        print('cart id exists')
        if ....

else:   

return render(request,"carts/home.html",{})

This may solve such issues

这可能会解决此类问题