pythondjango

In django how to have the template tag to load current date everyday?


I have created a dashboard in the index page of django which outputs using template tag code. This template tag has code like:

start = timezone.now().date()
end = timezone.now().date()+datetime.timedelta(days=1)

I give a date__range(start,end) for outputting records in the date range. If this server is running continuously over days, the template tag has the 1st day date stored. Without having to restart the server to execute this code, how do I get this code to execute everyday? Using django 1.6.5


Solution

  • My colleague had this problem a while back. You mentioned this is in the template tag file. I'll wager your file looks something like this:

    start = timezone.now().date()
    end = timezone.now().date()+datetime.timedelta(days=1)
    
    def my_template_function():
        # code goes here
    

    The issue with this code is that the start and end variables are only calculated once when the pyc (or whatever format you are using) file is generated. To make this work properly move your code inside the function of the template tag file like so:

    def my_template_function():
        start = timezone.now().date()
        end = timezone.now().date()+datetime.timedelta(days=1)
        # rest of the code goes here
    

    If that doesn't solve your problem please post some more code from your template tag file.