I am currently using Django 4.0 and trying to find a way to transform the following: [year] to the current year.
It needs to be automatically replaced every time [year] is found. Be it from the admin panel, from CKEDITOR, or comments, etc.
I can find ways to do this when [year] is hardcoded, but I don't know how to make it work when I am posting a blog post from Django Admin, for example.
To also add, I have tried using JS to transform the [year] tag to the current year. The problem with this is that it doesn't work on the page title or for search engines. They will still index the page with [year] instead of 2022, for example. Using JS works well for people, but not from a SEO perspective.
Your help would be appreciated! Thanks.
CodePudding user response:
It is quite simple:
Let's suppose we have a model called Post and it has a content field:
from datetime import date
current_year = date.today().year
new_post = Post.objects.last()
if "[year]" in new_post.content:
new_post.content.replace("[year]", str(current_year) )