2👍
✅
It’s because srv_time
is being set as a ‘class’ level attribute and not an ‘instance’ level attribute.
Python keeps two namespaces for both ‘class’ level attributes and ‘instance’ level attributes.
When Django gets loaded (when you start your server), it runs the calculation for srv_time
just once. This is why when you refresh the page it isn’t recalculating this value.
You’ll need to override the __init__
function of MyAdminSite
to have this calculation always run whenever the class gets instantiated as an object.
class MyAdminSite(AdminSite):
# Text to put at the end of each page's <title>.
site_title = ugettext_lazy('Test panel title')
# My custom variable
import datetime
srv_time = "%s" % datetime.datetime.now()
def __init__(self, *args, **kwargs):
super(MyAdminSite, self).__init__(*args, **kwargs)
self.srv_time = "%s" % datetime.datetime.now()
def each_context(self):
"""
Overriden dictionary of variables returned for
*every* page in the admin site.
"""
return {
'site_title': self.site_title,
'site_header': self.site_header,
'srv_time': self.srv_time,
}
Alternatively, you could just do the calculation in the each_context
function.
def each_context(self):
"""
Overriden dictionary of variables returned for
*every* page in the admin site.
"""
return {
'site_title': self.site_title,
'site_header': self.site_header,
'srv_time': "%s" % datetime.datetime.now(),
}
Source:stackexchange.com