2014-01-16 45 views
2

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

这里是事实/ urls.py代码:

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

urlpatterns = patterns('', 
    (r'^$', 'facts.main', d), 
) 

这种做法显示了从模型的数据,但我'不知道是否有一种方法可以在这里设置自定义标题?

我也试过另一种方法 - 我创造的事实/ 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 

和urls.py改变代码:

(r'^$', facts.views.fact), 

这种方法设置自定义标题,但没有按不显示模型中的数据。

任何帮助?

+0

你是不是在你的问题清楚,因为我没有看到任何有关您的响应的标题操作... Django涵盖了文档中的标题:https://docs.djangoproject.com/en/1.6/ref/request-response/#django.http.HttpRequest。 META – petkostas

+0

我在第二种方法中添加自定义标题(TestCustomHeader),并可以在萤火虫中看到它。但是在这种情况下,模型不会被加载。 – Phantom

+0

为什么要看模型数据?你实际上并没有在任何地方提取任何模型数据...... 你应该检查Django文档以获得进一步的理解: https://docs.djangoproject.com/en/1.6/topics/http/views/ – petkostas

回答

2

当您将字典传递给 urls.py时,函数def main()处理{"model_name": "Fact"}。也许还有像一些代码:

model = get_model(kwargs["model_name"]) 
return model.objects.all() 

当您通过“MODEL_NAME”到render_to_response,将字典传递到模板上下文。如果您包含在您的模板{{model_name}}中,则页面应呈现Fact。在基于类的意见


设置自定义标题,在类中定义的功能等:

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

    return response 

或函数中的观点:

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

    [ Some code to fetch model data ] 

    return response