How to setup menu data in Context_processor in Django?
Asked Answered
D

1

1

I have category and subcategory store in my database, and subcategory is related to category, I have multiple pages on my website, but I am able to display category in the menu on some pages, but I want to display on all pages, so I found the solution using context_processor, but I am unable to render HTML file there, it only takes data in the dictionary file, please check my code and let me know where I am mistaking.

here is my models.py file...

class Category(models.Model):
   cat_name=models.CharField(max_length=225)
   cat_slug=models.SlugField(max_length=225, unique=True)
   
   def __str__(self):
   return self.cat_name

class SubCategory(models.Model):
   subcat_name=models.CharField(max_length=225)
   subcat_slug=models.SlugField(max_length=225, unique=True)
   category = models.ForeignKey('Category', related_name='subcategoryies', on_delete=models.CASCADE, blank=True, null=True)
  
   def __str__(self):
   return self.subcat_name

here is my context_processor.py file...

from django.shortcuts import render
from dashboard.models import Category, SubCategory

def context_categories(request, cat_slug):
    category = Category.objects.all().order_by('-created_at')
    return render(request, "base.html", {'category':category})

included this file in settings.py file under TEMPLATES section

 'mainpage.context_processors.context_categories',

here is my base.html file...

{% for cat in category %}
      <li>
       <a href="javascript:void()">{{cat.cat_name}}</a>
          <ul>
           {% for subcat in cat.subcategoryies.all %}
            <li><a href="/subcategory/{{subcat.subcat_slug}}">{{subcat.subcat_name}}</a></li>
             {% endfor %}
           </ul>
       </li>
 {% endfor %}
Dacosta answered 27/7, 2020 at 10:20 Comment(2)
A contextprocessor only passes extra variables to the template render engine, so it returns a dictionary, and does not take any parameters (except for the request).Pendergast
The template tag is a much better way to realize itsPulsation
C
0

A context processor doesn't render a template. It should return a dictionary. And it should take only the request as a parameter. So your context_processor.py should look like this:

from dashboard.models import Category

def context_categories(request):

    category = Category.objects.all().order_by('-created_at')

return {
    'category':category 
}

Make sure the path to the context processor function is written in the context_processors list in the TEMPLATES setting.

Clevey answered 2/5, 2024 at 18:19 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.