简体   繁体   中英

Django custom response headers

I need to set custom response headers in Django project.

Here is code from facts/urls.py:

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

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

This approach shows data from model, but I'am not sure if there is a way to set custom headers here?

Also I tried another approach - I created facts/views.py with following function:

def fact(request):

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

    response['TestCustomHeader'] = 'test'

    return response

and changed code in urls.py:

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

This approach sets custom headers but doesn't show data from model.

Any help?

When you pass the dict to views.main in urls.py , the function def main() deals with {"model_name": "Fact"} . Probably there's some code like:

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

When you pass "model_name" to render_to_response , the dict is passed to the template as context. If you include in your template {{model_name}} , the page should render Fact .


Setting custom headings in Class Based views, inside the Class define a function like:

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

    return response

Or in a function view:

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

    [ Some code to fetch model data ]

    return response

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM