Reputation: 1021
I wanted to pass slug into ListView. But it was not as simple as passing it to DetailView.
That's because, ListView doesn't have built-in slug support.
I found answer of my question and I want to share with you, guys.
Upvotes: 1
Views: 507
Reputation: 1021
Note: I use ManyToMany field.
Models.py:
class Article(models.Model):
...
country = models.ManyToManyField('Country', related_name='country', blank=True)
...
class Country(models.Model):
name = models.CharField(max_length=50)
slug = models.SlugField(unique=True)
urls.py:
urlpatterns = [
path('<country>/', ArticlesListView.as_view(), name='articles-list'),
]
views.py:
from django.shortcuts import get_list_or_404
class ArticlesListView(ListView):
model = Article
template_name = 'articles/articles-list.html'
def get_queryset(self, *args, **kwargs):
return get_list_or_404(Article.objects.all().filter(topic__slug = self.kwargs['topic']))
Reference link: https://docs.djangoproject.com/en/3.1/topics/class-based-views/generic-display/#dynamic-filtering
Upvotes: 2