Last-Modified, 304 Not Modified, If-Modified-Since

I have a couple of static pages - like about and contact - which are there in the templates but the views don’t connect to a database or has any dynamic content.

I want to know how to send in Last-Modified header and the 304 Not Modified header for browsers sending in if-modified-since header to the Django app.

See the page on Conditional view processing for your different options in handling this.

So for static pages, do we hard set the latest_entry ?

from django.views.decorators.http import last_modified
latest_entry = '2021-09-16 14:30:59'

Caveat: I’ve never used this, I’m only reporting what I’m finding in the docs. I’d be interested in knowing if I’m misinterpreting anything that I’m reading.

From the docs in The condition decorator section:

The function passed last_modified_func should return a standard datetime value specifying the last time the resource was modified, or None if the resource doesn’t exist.

Then in the example later on:

def latest_entry(request, blog_id):
    return Entry.objects.filter(blog=blog_id).latest("published").published

So, you could create your latest_entry function to return a hard-coded value (but as a datetime value, not a string).

Or, if it’s a file in the file system, you could use the appropriate OS-level call to get the actual last-modified date of the file.

(Or you could create a table to track last modified dates in your database, or you could come up with some other idea.)

As I read this, it’s entirely up to you to determine what value to return from your function.

I get ‘datetime.datetime’ object is not callable
path\lib\site-packages\django\views\decorators\ in get_last_modified, line 83

from datetime import datetime ,timedelta

@last_modified(datetime(year=2021, month=9, day=16))
def about(request):
    return render(request, 'about.html')

Correct, because you’re not passing a function to the decorator. You’re passing a datetime value.

You must supply a function in the decorator.

Thank you very much, I have got this to work.

@last_modified(lambda request: datetime(year=2021, month=9, day=16))
def about(request):
    return render(request, 'about.html')
1 Like