How To Add Http Headers In Django Response

This example will tell you how to add http response headers in Django source code. This example is based on Django Bootstrap3 Example, but you can also create a new Django project to run this example.

1. Add Http Response Headers In Django View Function.

add dept emp views test case python file

The http response header is always added in the Django project view function before return the HttpResponse object to client. So edit the DjangoHelloWorld / dept_emp / file home_page function as below.

def home_page(request):

    # get the django.http.response.HttpResponse object
    resp = render(request, 'dept_emp/home_page.html')

    # set http response header and value.
    resp['Cache-Control'] = 'public,max-age=100000'

    resp['Vary'] = 'Accept-Encoding'
    # return the HttpResponse object. 
    return resp

2. Verify The Http Response Header & Values Via Google Chrome Developer Tools.

  1. Start the Django project application.
  2. Browse the web url in google chrome.
  3. Right click the page, click Inspect menu item in the popup menu list.
  4. Click Network tab in chrome inspector window.
  5. Select web resource in left panel, click Headers tab in right panel. Now you can see the added http response headers Cache-Control : public,max-age=100000 and Vary :Accept-Encoding.
    add http response headers in django source code
0 0 votes
Article Rating
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest Most Voted
Inline Feedbacks
View all comments

thanks. it works

Would love your thoughts, please comment.x