How to Pass Additional Context into a Class Based View (Django)?
Last Updated :
02 Nov, 2021
Passing context into your templates from class-based views is easy once you know what to look out for. There are two ways to do it - one involves get_context_data, the other is by modifying the extra_context variable. Let see how to use both the methods one by one.
Explanation:
Illustration of How to use get_context_data method and extra_context variable to pass context into your templates using an example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in django.
How to Create Basic Project using MVT in Django?
How to Create an App in Django ?
Method 1: Using get_context_data method
Inside the models.py add the following code:
Python3
from django.db import models
# Create your models here.
class YourModel(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
def __str__(self):
return self.first_name
After creating this model, we need to run two commands in order to create database for the same.
python manage.py makemigrations
python manage.py migrate
Create the folder named templates inside the app directory(geeks) , inside this folder add the file named Intro.html and add the following code:
HTML
<!-- Intro.html -->
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Intro</title>
</head>
<body>
<h1>All users name </h1>
{% for user in users %}
{{user.first_name}}
{% endfor %}
</body>
</html>
Inside the views.py file add the following code:
Python3
from django.views.generic.base import TemplateView
from .models import YourModel
class Intro(TemplateView):
template_name = 'Intro.html'
def get_context_data(self,*args, **kwargs):
context = super(Intro, self).get_context_data(*args,**kwargs)
context['users'] = YourModel.objects.all()
return context
Inside the urls.py file of project named geeksforgeeks add the following code:
Python3
from django.contrib import admin
from django.urls import path
from geeks.views import Intro
urlpatterns = [
path('admin/', admin.site.urls),
path('',Intro.as_view(),name="intro")
]
Method 2: Using extra_context variable
Rewrite the views.py flle by adding the following code:
Python3
from django.views.generic.base import TemplateView
from .models import YourModel
class Intro(TemplateView):
template_name = 'Intro.html'
extra_context={'users': YourModel.objects.all()}
By both the methods you will see the same output. Let's check what is there on http://localhost:8000/, before doing this don't forget to add some data to your model.
How to add data to your model
Django ORM – Inserting, Updating & Deleting Data
Output -
Similar Reads
How to Create and Use Signals in Django ? In this article, we'll dive into the powerful world of Django signals, exploring how to create and use them effectively to streamline communication and event handling in your web applications. Signals in DjangoSignals are used to perform any action on modification of a model instance. The signals ar
5 min read
How to create Abstract Model Class in Django? Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. Itâs free and open source. W
2 min read
How to Use permission_required Decorators with Django Class-Based Views In Django, permissions are used to control access to views and resources. When working with function-based views (FBVs), decorators like @permission_required are commonly used to restrict access based on user permissions. But what happens when we use class-based views (CBVs)?Django offers flexibilit
4 min read
Class based views - Django Rest Framework Class-based views help in composing reusable bits of behavior. Django REST Framework provides several pre-built views that allow us to reuse common functionality and keep our code DRY. In this section, we will dig deep into the different class-based views in Django REST Framework. This article assum
12 min read
How to Create a Basic Project using MVT in Django ? Prerequisite - Django Project MVT Structure Assuming you have gone through the previous article. This article focuses on creating a basic project to render a template using MVT architecture. We will use MVT (Models, Views, Templates) to render data to a local server. Create a basic Project: To in
2 min read
ListView - Class Based Views Django List View refers to a view (logic) to display multiple instances of a table in the database. We have already discussed the basics of List View in List View â Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do n
4 min read