Django FBV的“render_to_response”等效于基于类的视图?

时间:2013-08-12 11:27:46

标签: python django django-class-based-views

我现在正在将所有基于Django函数的视图转换为基于类的视图...

所以这是我的原始代码:

views.py

def search(request):        
    if 'q' in request.GET:
        q = request.GET['q']

        if q:
            result = Post.objects.filter(title__icontains=q)

    variables = RequestContext(request, {
        'result': result
    })

    return render_to_response('search.html', variables)

我只是为了练习CBV而试图将其转换为CBV ......

这是我到目前为止所做的:

views.py

class PostSearch(TemplateView):
    template_name = 'search.html'

    def get(self, request, *args, **kwargs):
        q = self.request.GET.get('q')
        if q:
            data = {
                'result': Post.objects.filter(title__icontains=q)
            }

            return self.render_to_response(data)

我认为这样可以正常工作,因为它是一个非常简单的代码。但是,我收到了这个错误:

ValueError: The view app_blog.views.PostSearch didn't return an HttpResponse object.

所以我认为“render_to_response”在CBV中完全不同......

将原始代码转换为CBV的正确方法是什么?

谢谢:((

2 个答案:

答案 0 :(得分:8)

class PostSearch(TemplateView):
    template_name = 'search.html'

    def get_context_data(self, **kwargs):
        context = super(PostSearch, self).get_context_data(**kwargs)
        q = self.request.GET.get('q')
        if q:
            context['result'] = Post.objects.filter(title__icontains=q)
        return context

答案 1 :(得分:2)

from django.shortcuts import render
from django.http import HttpResponse
class PostSearch(TemplateView):
    template_name = 'search.html'
    def get(self, request, *args, **kwargs):
        q = request.GET.get('q')
        if q:
            data = {
                'result': Post.objects.filter(title__icontains=q)
            }

            return render(request,self.template_name,data)
        return HttpResponse('Please type a search query')