How to Pass Additional Context into a Class Based View (Django)?
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.
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:
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:
Inside the views.py file add the following code:
Inside the urls.py file of project named geeksforgeeks add the following code:
Method 2: Using extra_context variable
Rewrite the views.py flle by adding the following code:
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
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