How to Determine Whether a Post Has Been Edited in Django


In this article, we show how to determine whether a post has been edited in Django.

So on many sites such as youtube, if a user has edited a material like a comment, then youtube will show that the comment originally posted has been edited.

You may want to do this on your site as well.

You want to be able to determine and display whether a post has been edited.

So the first thing we will do is create a Post model.

Within your Post model (or the model that stores the posts), you need to have 2 fields. These 2 fields are the date when the post was originally published and the last_edited field.

This Post model should resemble the following code shown below.

So within this Post model, we have the fields, title, url, content, content, pub_date, last_edited, author, likes, and dislikes.

Both pub_date and last_edited are both of type DateTimeField.

In for the field to simply be created with a single date at the time of creation, to the DateTimeField, we add, auto_now_add=True. With auto_now_add=True being added to the DateTimeField(), the date is added only once, at the time of creation.

Now, for the last_edited field, we also have a DateTimeField(), but we now add, auto_now=True. With auto_now=True, the date is updated every time there is a new POST request and save to the database.

So if a user creates a post and never edits it, the pub_date and the last_edited fields will have the same value.

If a user creates a post and then later edits it, the pub_date and the last_edited fields will have different values.

We can use an if statement in the template file that if the pub_date and last_edited fields have different values, then the post has been edited.

This is shown in the template file below of the detail.html of posts on the site.

On this detail post page, we have the title, content, author of each post.

If eachpost.pub_date is not equal to eachpost.last_edited, then the post has been edited, and we write this in within p tags. If this isn't true, then the post hasn't been edited, so display nothing.

And this is really a simple and effective way of determining whether a post has been edited in Django.

Related Resources

How to Randomly Select From or Shuffle a List in Python

HTML Comment Box is loading comments...