Unable to use the value in a dictionary in one Django view in another Django view (AttributeError: module 'urllib.request' has no attribute 'session')
I am new to using Django. I have a function in views.py that computes the profit and prints it to a webpage in Django. I store the profit in a dictionary by the name of context
and then store it in a session:
#We want to calculate hourly profit
def profitmanagement(request):
#Profit has already been computed
context={'TotalHourlyProfit':TotalProfit}
#We will pass this dictionary to our ProfitManagement.html template. This will display our total profit.
request.session['context'] = context #Save the dictionary using a session to use in another function
return render(request,"ProfitManagement.html",context)
Now I have another function that will be triggered every hour using APScheduler. It should set the TotalHourlyProfit
to zero, and then output it to the webpage. It is as given below:
#Sets the hourly profit to zero at each hour
def ClearHourlyProfit():
context = request.session.get('context') #Loads the dictionary computed in profitmanagement(). This is returning an error
context['TotalHourlyProfit']=0 #Set the hourly profit to zero.
#print("Hourly profit function has context:",context)
return render(request,"ProfitManagement.html",context)
It returns the error:
AttributeError: module 'urllib.request' has no attribute 'session'
Is there a way by which I can pass the changed value of TotalHourlyProfit
to my webpage? I will be very grateful to anyone who can point me in the right direction.
Thank you in advance!
You need to pass request
as an argument in ClearHourlyProfit()
function as well since it is a view function and also use {}
empty dict if context
does not exist so:
def ClearHourlyProfit(request):
context = request.session.get('context', {})
context['TotalHourlyProfit']=0
request.session['context'] = context
return render(request,"ProfitManagement.html",context)