Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to automatically replace a word with another?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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)  )
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading