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