2016-06-15 7 views
0

私はDjangoでクラスベースのビューを学習しており、ViewやTemplateViewのような基本的な一般的なビューで作業する方法を学んだ。カスタムヘッダークラ​​スベースのビューを設定するDjango

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 

答えて

0

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 
関連する問題