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

时间:2015-04-20 09:56:29

标签: python django

urls.py

from housepost.views import ListingPost
...
url(r'^house_post/$', ListingPost.as_view(), name='post_house'),
...

views.py

from django.http import HttpResponse
from django.contrib import messages
from django.views.generic import View
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator

class ListingPost(View):

    def get(self, request, *args, **kwargs):
        messages.error(request, 'asdf', extra_tags = 'error')
        return HttpResponse('Hi')

    @method_decorator(login_required)
    def dispatch(self, *args, **kwargs):
        super(ListingPost, self).dispatch(*args, **kwargs)

我在get请求中返回了一个HttpResponse,但我一直收到错误:

错误消息

  

视图housepost.views.ListingPost未返回HttpResponse对象。它改为返回None。

我哪里错了?

2 个答案:

答案 0 :(得分:4)

dispatch会返回HttpResponse,但是当您覆盖它时,您不会返回任何内容。这是调用getpost并代表他们返回响应的方法。所以以下内容应该有效:

def dispatch(self, *args, **kwargs):
    return super(ListingPost, self).dispatch(*args, **kwargs)

答案 1 :(得分:1)

您的调度方法需要实际返回调用超类方法的结果:

return super(ListingPost, self).dispatch(*args, **kwargs)