Anjanesh Lekshminarayanan
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:

UPDATED: I made a mess of the previous code which was re-done and then refactored it wrongly to return a string. This would fail as @last_modified requires a function returning a datetime

import os.path
from datetime import datetime
from myproject.settings import BASE_DIR # Replace myproject with the name of your project

def date_last_modified_static(request, app, template_name):

    template_file_path = os.path.join(str(BASE_DIR) + '/' + app + '/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)    

    dt = datetime.fromtimestamp(mtime)

    return dt


# Replace myapp with your app name
@last_modified(lambda request: date_last_modified_static(request, 'myapp', 'about.html'))
def about(request):
    return render(request, 'about.html')

Reference : docs.djangoproject.com/en/3.2/topics/condit..

 
Share this