What is the correct way of using Django's get_context_data() method to add key-value pairs to a context?
How can Django's get_context_data() method be used to add new key-value pairs to a context in the views.py file? I am following along with a tutorial and thus far everything has worked well, however at the moment I can't get the added context entries to populate the html template. Here's what I've got thus far, based on the instructions in the tutorial:
views.py:
from django.shortcuts import render
from django.views.generic import TemplateView
# Create your views here.
def home_page_view(request):
context = {
"inventory_list": ["Widget 1", "Widget 2", "Widget 3"],
"greeting": "THanK yOu foR viSitiNG!",
}
return render(request, "home.html", context)
class AboutPageView(TemplateView):
template_name = "about.html"
def get_context_data(self, **kwargs): # new
context = super().get_context_data(**kwargs)
context["contact_address"] = "123 Jones Street"
context["phone_number"] = "01234 678910"
return context
about.html (the template):
<h1>Company About Page</h1>
<p>The company address is {{contact_address}}.</p>
<p>The company phone number is {{phone_number}}.</p>
urls.py:
from django.urls import path
from .views import home_page_view, AboutPageView
urlpatterns = [
path("about/", AboutPageView.as_view()),
path("", home_page_view)
]
This results in an output which doesn't drag through the values associated contact_address and phone_number to the website when I run the dev server:
What I am doing wrong? I've double-checked the sample code several times, and can't see that I'm mis-typing anything. I've also browsed for solutions online but many of the responses seem to relate to scenarios that are a bit far ahead of my beginner-level understanding. I've only been dealing with Django for a week, so I'm prepared to accept that I might be missing something quite elementary.
I'm running Django 5.0.13 with Python 3.12.1, on a Windows 11.
Thanks in advance.
I have now resolved this - the issue stems from not including the get_context_data() method as part of the AboutPageView class. The problem stemmed from the formatting of the tutorial materials, which made it hard to read indentation.
Mods: given the nature of the error, please let me know if this question merits removal due to it being of limited use to the community.
Here is the correct version of the code
class AboutPageView(TemplateView):
template_name = "about.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["contact_address"] = "123 Jones Street"
context["phone_number"] = "01234 678910"
return context