[英]How to pass a parameter to Class based views in Django?
how to pass this parameter in the class called?如何在调用的class 中传递这个参数?
This is url这是 url
#url
path('all-agency/<int:id>', AllAgenciesView.as_view(), name='all-agency'),
cbv 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')
.现在我想将“id”传递到基于 class 的视图中,但是当我
filter(id=self.kwargs['id')
时。 I Got returned KeyError: 'id'
我得到了返回
KeyError: 'id'
i tried another way which is我尝试了另一种方式
filter(id=self.kwargs.get('id'))
and it returned None
when i print(agencies)
当我
print(agencies)
时它返回None
(代理)
another way ive tried我试过的另一种方法
filter(id=self.request.GET.get('id'))
this also returned the same None
这也返回了相同的
None
You're calling the wrong view in your paths, you should call AllAgenciesListView
instead of AllAgenciesView
.您在路径中调用了错误的视图,您应该调用
AllAgenciesListView
而不是AllAgenciesView
。
Corrected version:修正版:
#url
path('all-agency/<int:id>', AllAgenciesListView.as_view(), name='all-agency'),
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.