视图没有返回HttpResponse对象。它返回了None

时间:2014-10-08 14:04:27

标签: python django django-views

我有以下简单的观点。为什么会导致此错误?

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))

4 个答案:

答案 0 :(得分:58)

因为视图必须返回 render,所以不要只是调用它。将最后一行更改为

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

答案 1 :(得分:2)

使用UpdateView时出现了同样的错误

我有这个:

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

我解决了这个问题:

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

答案 2 :(得分:2)

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

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

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

以上代码可以更改为

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

else:   

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

这可以解决此类问题

答案 3 :(得分:0)

Python对缩进非常敏感,下面的代码我遇到了相同的错误:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
            return render(request, "calender.html")

正确的缩进是:

    except IntegrityError as e:
        if 'unique constraint' in e.args:
        return render(request, "calender.html")