Anjanesh

Anjanesh

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. views.py:

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)

    # https://thispointer.com/python-get-last-modification-date-time-of-a-file-os-stat-os-path-getmtime/
    mtime = os.path.getmtime(template_file_path)

    # https://docs.python.org/3/library/datetime.html#datetime.datetime
    dt = datetime.fromtimestamp(mtime)

    # https://stackoverflow.com/a/69737507/126833
    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 : docs.djangoproject.com/en/3.2/topics/condit..

 
Share this