How to pass a parameter to Class based views in Django?
how to pass this parameter in the class called?
This is url
#url
path('all-agency/<int:id>', AllAgenciesView.as_view(), name='all-agency'),
cbv
#views
class AllAgenciesView( TemplateView):
template_name='agencies.html'
class AllAgenciesListView(ServerSideDatatableView):
def get_queryset(self):
agencies = SettingsAgency.objects.using('agency-namespace').filter(id=self.kwargs['id'])
return agencies
this is in template
#in anchor tag(html)
<a href="{% url 'all-agency' id=2 %}" ><div>Agencies</div></a>
in address bar it would look like this:
http://127.0.0.1:8000/all-agency/2
Now I want to pass the 'id' into the class based views but when i did filter(id=self.kwargs['id')
. I Got returned KeyError: 'id'
i tried another way which is
filter(id=self.kwargs.get('id'))
and it returned None
when i print(agencies)
another way ive tried
filter(id=self.request.GET.get('id'))
this also returned the same None
You're calling the wrong view in your paths, you should call AllAgenciesListView
instead of AllAgenciesView
.
Corrected version:
#url
path('all-agency/<int:id>', AllAgenciesListView.as_view(), name='all-agency'),