Django自定义响应标头

Pha*_*tom 5 python django custom-headers

我需要在Django项目中设置自定义响应标头。

这是来自facts / urls.py的代码:

d = {
    'app_name': 'facts',
    'model_name': 'Fact'
}

urlpatterns = patterns('',
    (r'^$', 'facts.main', d),
)
Run Code Online (Sandbox Code Playgroud)

这种方法显示模型中的数据,但是我不确定是否可以在此处设置自定义标头?

我还尝试了另一种方法-我使用以下功能创建了facts / views.py:

def fact(request):

    response = render_to_response('facts.html', 
                                  {'app_name': 'facts',
                                   'model_name': 'Fact'}, 
                                  context_instance=RequestContext(request))

    response['TestCustomHeader'] = 'test'

    return response
Run Code Online (Sandbox Code Playgroud)

并更改了urls.py中的代码:

(r'^$', facts.views.fact),
Run Code Online (Sandbox Code Playgroud)

此方法设置自定义标头,但不显示模型中的数据。

有什么帮助吗?

xbe*_*llo 5

当您将字典传递给views.mainin时urls.py,该函数将def main()处理{"model_name": "Fact"}。可能有一些类似的代码:

model = get_model(kwargs["model_name"])
return model.objects.all()
Run Code Online (Sandbox Code Playgroud)

当您将“ model_name”传递给时render_to_response,字典将作为上下文传递到模板。如果包含在模板中{{model_name}},则页面应呈现Fact


在“类”内部的“基于类”视图中设置自定义标题,可定义如下函数:

def get(self, request):
    response = HttpResponse()
    response["TestCustomHeader"] = "test"

    return response
Run Code Online (Sandbox Code Playgroud)

或在功能视图中:

def main(request):
    response = HttpResponse()
    reponse["TestCustomHeader"] = "test"

    [ Some code to fetch model data ]

    return response
Run Code Online (Sandbox Code Playgroud)