6

When a user requests the same page, with the same data...I'd like Django to return a 304, so that the browser doesn't have to load the page all over again.

I'm new to this. How can this be done?

Thanks.

TIMEX
  • 259,804
  • 351
  • 777
  • 1,080

2 Answers2

13

There's extensive description in Django documentation: Conditional view processing

Following tools are particularly useful:

  1. @last_modified and @etag view decorators. You supply them with a function to compute the value from request and everything else is done automatically.
  2. django.middleware.http.ConditionalGetMiddleware -- it generates required ETag and returns 304 if there's a cache hit, but this still takes server time to generate full HTML and only network time is saved. Still very good for one-line configuration change.
Dan
  • 12,409
  • 3
  • 50
  • 87
Alexander Lebedev
  • 5,968
  • 1
  • 20
  • 30
6

You could look into Django's caching system, or if you can easily check if the user is requesting the same data, you can return a HttpResponseNotModified() - this returns a 304. Check out the docs here.

hora
  • 3,661
  • 5
  • 25
  • 26
  • 2
    Server-side caching is useful, but unrelated to HTTP 304. And it's true that you can return HttpResponseNotModified yourself, but Django already has built-in mechanisms to check for same response and return the 304 for you; see Alex Lebedev's answer. – Carl Meyer Feb 18 '10 at 13:15
  • Thanks Carl, I didn't know that! I've still got a ton to learn about Django. – hora Feb 19 '10 at 20:32