Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 517
Phantom Avatar asked Jan 16 '14 15:01

Phantom


People also ask

What is HttpResponse in Django?

HttpResponse (source code) provides an inbound HTTP request to a Django web application with a text response. This class is most frequently used as a return object from a Django view.

What is QueryDict Django?

In an HttpRequest object, the GET and POST attributes are instances of django. http. QueryDict , a dictionary-like class customized to deal with multiple values for the same key. This is necessary because some HTML form elements, notably <select multiple> , pass multiple values for the same key.

How do I get the HTTP response header?

getKey() + " ,Value : " + entry. getValue()); } //get header by 'key' String server = conn. getHeaderField("Server");

What are Middlewares in Django?

Middleware is a framework of hooks into Django's request/response processing. It's a light, low-level “plugin” system for globally altering Django's input or output. Each middleware component is responsible for doing some specific function.


1 Answers

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()
    response["TestCustomHeader"] = "test"

    [ Some code to fetch model data ]

    return response
like image 178
xbello Avatar answered Oct 08 '22 15:10

xbello