0

i recently created a category system but the problem is that when ever i go to another page that isn't the home page, all the categories go away because i haven't referenced them. i found that by adding

    def get_context_data(self, *args, **kwargs):
        cat_menu = Category.objects.all()
        context = super(CategoryView, self).get_context_data(*args, **kwargs)
        context["cat_menu"] = cat_menu
        return context

below each view then it would allow the categories in all my pages. but because for a few views i used function based views and since i can't for example do:

def CategoryView(request, cats):
    category_posts = Post.objects.filter(category=cats)
    return render(request, 'blog/categories.html', {'cats':cats, ' 
    category_posts':category_posts})

    def get_context_data(self, *args, **kwargs):
        cat_menu = Category.objects.all()
        context = super(CategoryView, self).get_context_data(*args, **kwargs)
        context["cat_menu"] = cat_menu
        return context

i need to convert

def CategoryView(request, cats):
    category_posts = Post.objects.filter(category=cats)
    return render(request, 'blog/categories.html', {'cats':cats, ' 
    category_posts':category_posts})

to a class based view.

i first tried doing this:

class CategoryView(ListView):
template_name = 'blog/categories.html'
model = Post
context_object_name = "category_posts"

def get_queryset(self):
    return super().get_queryset().filter(category=self.kwargs.get('cats'))


def get_context_data(self, *args, **kwargs):
    cat_menu = Category.objects.all()
    context = super(CategoryView, self).get_context_data(*args, **kwargs)
    context["cat_menu"] = cat_menu
    return context

but when i rendered out the template i lost the {{cats}} - categories any help would be appreciated

pyguy34
  • 11
  • 3
  • 1
    Does this answer your question? [Access kwargs from a URL in a Django template](https://stackoverflow.com/questions/45098826/access-kwargs-from-a-url-in-a-django-template) – Abdul Aziz Barkat Aug 03 '22 at 17:03
  • you don't have any cats in context to render {{ cats }}. Probably you mean {{ cat_menu }} ? – Maxim Danilov Aug 03 '22 at 19:28

0 Answers0