我正在学习 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 …Run Code Online (Sandbox Code Playgroud)