Title: Can you pass an argument to ListView in Django?
Tags: django;listview;django-views
Question: I am creating a Fixture webapp with Django. I have written the class below, which displays a list of first team fixtures. Can I rewrite it as TeamView, then pass the team_id?
class FirstView(generic.ListView):
template_name = 'fixtureapp/team.html'
context_object_name = 'fixtures'
def get_queryset(self):
&quot;&quot;&quot;return all first team matches&quot;&quot;&quot;
return Match.objects.filter(team_id=1).order_by('date')
def get_context_data(self, **kwargs):
data = super().get_context_data(**kwargs)
data['page_title'] = '1st Team Fixtures'
return data
I have the following urls, how would I rewrite these to match?
urlpatterns = [
path('', views.HomeView.as_view(), name='home'),
path('first', views.FirstView.as_view(), name='first'),
path('second', views.SecondView.as_view(), name='second'),
as you can see I have currently created a second class called SecondView this is almost a carbon copy of FirstView, not very DRY

Here is the accepted answer: I can give you a brief of how it works, you can apply rest of the logic. Basic idea is to use slug.
In your html you can give the slug name with the url:
<a href=&quot;{% url 'team_by_id' teamid.slug %}&quot;&gt;</a&gt;
In urls.py, get that slug :
path('team/<slug:teamid_slug&gt;/', views.TeamView.as_view(), name='team_by_id'),
Your Views should filter the query based on this slug, if no slug given it will give all the Match record. You can apply some other logic what fits to you.
class TeamView(generic.ListView):
queryset = Match.objects.all().order_by('date')
template_name = 'fixtureapp/team.html'
context_object_name = 'fixtures'
def get_queryset(self):
&quot;&quot;&quot;return all team_id team matches&quot;&quot;&quot;
return Match.objects.filter(team_id__slug=self.kwargs.get('teamid_slug')).order_by('date')
Also please have a look at this documentation of Dynamic Filtering
Comment for this answer: This looks like exactly what I was looking for. I am having trouble mapping the url to make it work. Need to study it a bit more but thanks for pushing me in the right direction.
Comment for this answer: Its now working. I changed team_id__slug= to just team_id. When calling url I used  where 6 was the team id


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2021:00:03/06/21', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<django><listview><django-views>', 'Title': 'Can you pass an argument to ListView in Django?', 'ViewCount': 242, 'id': 66511758, 'user_AboutMe': None, 'user_AccountId': 20863116.0, 'user_DisplayName': 'Martin Slater', 'user_Reputation': 23.0, 'user_Views': 3.0, 'user_id': 15324846.0}}