我有一个页面列出了基于类别的文章。 类别是从网址中的条目过滤出来的。
我想在模板中显示带有类别名称的标签。
通过get_context_data
,我可以检索该段并将其用作{{categoryslug}}
,但如何根据段来获取类别的名称?
Model.py
class Category(models.Model):
name = models.CharField(max_length=50,unique=True, blank=True)
slug = models.SlugField(max_length=100,unique=True, blank=True)
def __str__(self):
return self.name
class Article(models.Model):
title= models.CharField(max_length=40, blank=True)
category = models.ForeignKey('Category', on_delete= models.PROTECT, related_name="pcat", blank=True)
def __str__(self):
return self.title
View.py
class ListArticleView(ListView):
model = Article
context_object_name = "listcat"
template_name = "myapp/categories.html"
paginate_by = 5
def get_queryset(self):
return Article.objects.filter(category__slug=self.kwargs['cat_slug'])
def get_context_data(self, **kwargs):
context=super(ListArticleView,self).get_context_data(**kwargs)
context['categoryslug']=self.kwargs['cat_slug']
return context
URLS.py
path(('/<cat_slug>'), views.ListArticleView.as_view(), name='some_categories'))