3

I am learning Class Based Views in Django and have learnt to work with the base generic views like View and TemplateView.

I was playing with the generic view like ListView and DetailView, then I stumbled to a problem. How can we add custom header in a Class Based View that inherits from one of the view classes like ListView and DetailView.

I searched it on the but all the answers of function based views.

I have been able to set headers in the Class Base Views that inherit from the View class.

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

Can anybody tell me how to add a custom header in Class Based View that inherits from ListView or any other View like 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
AkshAy ShaRma
  • 31
  • 2
  • 2

1 Answers1

5

I would override the dispatch method. Call super() to get the response, set the headers, then return the response. Note you shouldn't need to call __setitem__ - just treat the response as a dictionary.

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
Alasdair
  • 298,606
  • 55
  • 578
  • 516