Chapter 4. Create CRUD Web Application

Customize Views (3) – Add Extra Context

Customize Views (3) – Add Extra Context
Tag:

The context data are already generated when you specify the model or queryset attribute. By overriding the get_context_data method, you can also add new context data. Here we'll explain how to add extra context with the employee learning app example.

1. Override the get_context_data method

In this case, we'll add new context data 'today'. In views.py, add import the datetime function so that you can use it in the overriding method.

In the CourseList view, override the get_context_data method like shown in the yellow code part below.

employee_learning/views.py
from django.urls import reverse_lazy
import datetime

class CourseList(ListView):
      :
    queryset = LearningCourse.objects.filter(title__contains='Docker')
      :
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['today'] = datetime.date.today()
        return context

2. Add the new context in the template file

Now, a new context, 'today', is available. To display it on the List page, update the course_list.html file. Add the yellow part of the code below.

templates/employee_learning/course_list.html
{% block body %}

<h1 class="text-center mt-5">LIST Page</h1>
<p class="text-muted text-center mb-5">As of {{ today }}</p>
    :

When you go to the list page, you can see that the extra context data is displayed on the list page.

Customize-Views-3--Add-Extra-Context

The context data are already generated when you specify the model or queryset attribute. By overriding the get_context_data method, you can also add new context data. Here we'll explain how to add extra context with the employee learning app example.

1. Override the get_context_data method

In this case, we'll add new context data 'today'. In views.py, add import the datetime function so that you can use it in the overriding method.

In the CourseList view, override the get_context_data method like shown in the yellow code part below.

employee_learning/views.py
from django.urls import reverse_lazy
import datetime

class CourseList(ListView):
      :
    queryset = LearningCourse.objects.filter(title__contains='Docker')
      :
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['today'] = datetime.date.today()
        return context

2. Add the new context in the template file

Now, a new context, 'today', is available. To display it on the List page, update the course_list.html file. Add the yellow part of the code below.

templates/employee_learning/course_list.html
{% block body %}

<h1 class="text-center mt-5">LIST Page</h1>
<p class="text-muted text-center mb-5">As of {{ today }}</p>
    :

When you go to the list page, you can see that the extra context data is displayed on the list page.

Customize-Views-3--Add-Extra-Context

Tag: