𝗛𝗼𝘄 𝗜 𝗟𝗲𝗮𝗿𝗻𝗲𝗱 𝗔𝗯𝗼𝘂𝘁 𝗖𝗼𝗻𝘁𝗲𝘅𝘁 𝗣𝗿𝗼𝗰𝗲𝘀𝘀𝗼𝗿𝘀 𝗶𝗻 𝗗𝗷𝗮𝗻𝗴𝗼
I am building an online accessories shop with Django.
I built a navbar to show product categories. At first, I hard-coded the categories. This worked for a while.
Then I saw a problem. If I add a new category, I must update the navbar manually. This is inefficient.
My first thought was to pass categories through the context in my view. I soon saw a second problem. Every page needs the navbar. This means I would repeat the same code in every single view. This creates messy code.
I found a better way: Django Context Processors.
Context processors make data available to all templates. You do not need to pass data from every view.
Use context processors for:
- Navigation categories
- Site settings
- User notifications
- Shopping cart data
A context processor is a Python function. It takes a request object and returns a dictionary.
Example:
def custom_context(request): return { "custom_value": "hello from context processors" }
You must register the function in your settings. Add it to the context_processors list inside the TEMPLATES setting.
Example:
'OPTIONS': { 'context_processors': [ 'myapp.context_processors.custom_context', ], },
Now, you use the data in your templates like this:
{{ custom_value }}
This solved my problem. My navbar now gets category data automatically on every page. I no longer duplicate code.
Building features often teaches you new concepts. For me, this was context processors.
Source: https://dev.to/merdas369/how-i-learned-about-context-processors-in-django-5e2h