'Django : local variable 'date' referenced before assignment but I import it

I am building a script that use the datetime module :

def workspace_detail(request, token):
yesterday = date.today() -  timedelta(days=1)
tomorrow = date.today() - timedelta(days=1)
quicklink = f"{token}start_date={yesterday}&end_date={tomorrow}"
w_yesterday = quicklink

But I have this error

local variable 'date' referenced before assignment

I imported it every module from the datetime package

from datetime import datetime, date, timedelta

If I use datetime.today() it works, but I want to use the date.today() for my url.

Thanks



Solution 1:[1]

Are you using the word "date" as a variable anywhere else in your function or script?.

This happened to me and the fix was to rename any variable named "date" and only use that keyword for the date object.

Solution 2:[2]

Just use blueprints and give your view the endpoint date.today

Solution 3:[3]

Are you using the word "date" as a variable anywhere else in your function or script? The problem is caused because you have used the date variable in your code. Sometimes it is not possible to change or rename all the variables if we used them more than 500 times. It will change the functionality of a program.
So the solution is, instead of importing the module as, from datetime import date, you can use an alias name like this: from datetime import date as date_function

then from this:

today = date.today()

change to this:

today = date_function.today()

Hope this is helpful for you!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Debo Akeredolu
Solution 2 Koralp Soy
Solution 3 Suraj Rao