Django extra_context Is Evaluated Once, get_context_data on Every Request
A class-based view can add template variables in two ways. extra_context is a class attribute: its dictionary is built once, when Python loads the module. get_context_data() is a method: it runs on every request. Anything that depends on time, the user or the database belongs in the method.
The Stale Value Trap
class DashboardView(LoginRequiredMixin, TemplateView):
template_name = "accounts/dashboard.html"
login_url = "signin"
extra_context = {"today": datetime.today()} # computed at import time
today is fixed to the moment the server process started. With Gunicorn workers running for days, the dashboard keeps showing that date until the next restart, and different workers can even show different dates.
Compute Per-Request Values in get_context_data
class DashboardView(LoginRequiredMixin, TemplateView):
template_name = "accounts/dashboard.html"
login_url = "signin"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["today"] = timezone.localdate()
context["open_tasks"] = self.request.user.tasks.filter(done=False)
return context
Always call super() first: parent classes and mixins add their own context (the object for a DetailView, the page for a ListView).
References
- Django MOC - hub for Django notes.
- Django documentation: ContextMixin -
extra_contextandget_context_data(). - Django documentation: Adding extra context - overriding
get_context_data().
Review cards
Flashcard Why is `extra_context` evaluated only once?
Because it is a class attribute, its dictionary is built when the module is imported, not on each request.
Flashcard What is the consequence of using `extra_context` for time-dependent data?
The data will be fixed to the moment the server process started, and will not update until the next server restart.