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

datetime.date.today() always returns the same value

I have a Django project. I use nginx + gunicorn.
The views.py file has a combined_data() function that creates and returns an HTML page. As you can see, I am passing the objects in ‘rows’ and the current date in ‘time’.

enter image description here

A function that returns objects looks like this

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

enter image description here

The problem is that in this function, reporting_date always gets the value it got the first time it was called.
For example, I do "sudo systemctl restart gunicorn" and open this page in the browser. reporting_date will be equal to today. If I open the page tomorrow, reporting_date will not change its value.

Initially, I assumed that datetime.date.today () does not work correctly, so I added the ‘time’ parameter to views.py (first screen), but the date is always correct there.
Then I thought that the default value of the parameters of the get_combined() function (second screen) is somehow cached, so I added the r_int parameter, which receives a random value, but everything works correctly here. r_int always gets a new value.

Now, I have to call "sudo systemctl restart gunicorn" every day to make the page work properly ((

Any ideas how to fix this problem? Thanks

>Solution :

Instead of

def get_combined(reported_date=datetime.datetime.today()):

use

def get_combined():
    reported_date = datetime.datetime.today()

What I tried:-

>>> def c(day = datetime.today()):
        print(day)

    
>>> c()
>>> 2022-10-27 15:44:57.593444
>>> c()
>>> 2022-10-27 15:44:57.593444
>>> def c():
        day = datetime.today()
        print(day)

    
>>> c()
>>> 2022-10-27 15:56:02.459517
>>> c()
>>> 2022-10-27 15:56:04.630902

As @OldBill mentioned: When you declare a default value for a function parameter it is evaluated once and not every time the function is called

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