Setting the Last-Modified header for a static page in Django

I once asked about 304 Not Modified headers on serverfault . That was 11 years back. I don't know why this is not a commonly implemented method by developers using frameworks.

If the page's last modified date stamp is set and the browser requests for the same page more than once, then the browser can retrieve the HTML content from it's cache instead of making a roundtrip to the server for getting back the same HTML content.

Here's a way to set the last modified header of an about page in Django.

from datetime import datetime
from django.views.decorators.http import last_modified
import os.path
from myproject.settings import BASE_DIR # Replace myproject with the name of your project

def date_last_modified_static(request, template_name):

    # Replace myapp with your app name
    template_file_path = os.path.join(BASE_DIR + '/myapp/templates/', template_name)

    mtime = os.path.getmtime(template_file_path)

    dt = datetime.fromtimestamp(mtime)

    FORMAT_STR = "Date: %a, %d %b %Y %H:%M:%S GMT"
    return dt.strftime(FORMAT_STR)

@last_modified(lambda request: date_last_modified_static(request, 'about.html'))
def about(request):
    return render(request, 'about.html')

Reference :

Share this