Skip to content
Related Articles

Related Articles

Improve Article

How to Pass Additional Context into a Class Based View (Django)?

  • Last Updated : 15 Jan, 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://loaclhost: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 – 

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :