DEV Community

Cover image for Django Context Processor
Mahmoud Ahmed
Mahmoud Ahmed

Posted on

Django Context Processor

today we will take about the django context processor
first lets imagine that we are building an Ecommerce Website, so our website will have products where clients can add to the cart then move to the checkout page and complete the process by adding their location and payment information or complete shopping and add more products to the cart

Image description

so in every page of the site the client can see the cart with the product that he added before and their quantity and price

so when developing this, we need to include the cart with all of it’s information in every view in our project, and this a really a bad solution, because Django uses DRY concept which means Do Not Repeat Yourself, here the context processor comes to fix this issue,

the context processor is a way to include something in all the site

or what if we want to add the site footer , so the footer we be in all the pages so we need to include it the footer information in all the views or create a context processor for the site footer

so now we should create a context processor for get footer or cart information instead of including that information in all the views in our project, but how can we create a context processor

Creating Context Processor
1 — I will create a new folder in the main project folder with the name of utils I always do this to add all the utils files in this folder (you can name it any name you want) or you can create the file in the app directory

2 — create a new python file with a meaningful name so I will call it settings_context.py for getting footer information then start adding the context processor code in it

Image description

so here i imported the footer model then I added a function to get the footer information, it is just a normal Django view that retrieves only one context ‘footer’

in the screenshot I also added another view to get the site logo now we need to include this view in our context processor in our settings.py

3 - so we will open settings.py then move to the templates part then add our context processors for footer and the other for the logo

Image description

and if you created a context for cart you will include it also

so now the footer and the logo from our context will be available in all the project templates and we can use it like any context we will include it in {footer.anyinfo} like any template context

now you do not have to include those information in any view

you should use the Django context processor any time you found
yourself need something in all the project pages

if you have any questions leave it below , follow me for more content related to Django , python , data science , machine learning and vuejs

Top comments (0)