设置自定义标题类基于视图Django

时间:2016-06-15 15:17:12

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

我正在学习Django中的基于类的视图,并学会了使用View和TemplateView等基本通用视图。

我正在使用像ListView和DetailView这样的通用视图,然后我偶然发现了一个问题。 我们如何在基于类的视图中添加自定义标头,该视图继承自ListView和DetailView之类的视图类。

我在基于函数的视图的所有答案上搜索了它。

我已经能够在继承自View类的类基本视图中设置标题。

class MyView(View):
    http_method_names=['post','get']
    message='<div id="myview">This is a class based view response.</div>'
    content_type='text/html'
    charset='utf-8'
    template_name='base.html'

    @method_decorator(gzip_page)
    @method_decorator(condition(etag_func=None,last_modified_func=None))
    def get(self,request,*args,**kwargs):
        response=TemplateResponse(request,self.template_name,{'number':1,'number_2':2})
        response.__setitem__('x-uuid',uuid.uuid4().hex)     #set header explicitly
        response.__setitem__('status',200)
        response.__setitem__('page_id',str(uuid.uuid4().hex))
        patch_vary_headers(response,['Etag','Cookie','User-Agent'])
        patch_cache_control(response)
        return response

    #Override this method to tell what to do when one of the methods in http_method_names is called
    def http_method_not_allowed(request, *args, **kwargs):
        response=HttpResponse("Method not allowed",status=405)
        response.__setitem__('x-uid',uuid.uuid4().hex)      #set header explicitly
        response.__setitem__('status',405)
        response.__setitem__({'hello':'word'})
        return response
        #return any type of response here
    # return JsonResponse(status=405,data={'not_allowed':True})

任何人都可以告诉我如何在基于类的视图中添加自定义标头,该标头继承自ListView或任何其他视图,如DetailView。

 class GetParticularUserView(ListView):
     http_method_names=['get']
    template_name='one_user.html'
    # context_object_name='user'        # set context either by this or by get_context_data
    '''queryset=User.objects.all()'''   # one way to set the data in the context

    def get_queryset(self):
        # define the query set to be used here.
        self.user=get_object_or_404(User,id=self.kwargs['id']) 
        return self.user

    def get_context_data(self,**kwargs):
         context=super(GetParticularUserView,self).get_context_data(**kwargs)
        context['user']=self.user
        return context

1 个答案:

答案 0 :(得分:2)

我会覆盖dispatch方法。调用super()以获取响应,设置标头,然后返回响应。请注意,您不需要调用__setitem__ - 只需将响应视为字典。

class GetParticularUserView(ListView):

    @method_decorator(gzip_page)
    @method_decorator(condition(etag_func=None,last_modified_func=None))
    def dispatch(self, *args, **kwargs):
        response = super(GetParticularUserView, self).dispatch(*args, **kwargs)
        response['x-uid'] = uuid.uuid4().hex  # set header
        return response