简体   繁体   English

在基于类的视图中获取kwargs的最佳方法?

[英]Best Way to get kwargs in a class based view?

I have a class based Django view: 我有一个基于类的Django视图:

class LocationView(TemplateView):

I have defined a named parameter in my url dispatcher: 我在url调度程序中定义了一个命名参数:

url(r'^locations/(?P<id>\d+)/$', LocationView.as_view(), name="location")

I know I can access my id parameter in a class method like get_context_data , where I can pass in **kwargs to the method itself. 我知道我可以在像get_context_data这样的类方法中访问我的id参数,在这里我可以将** kwargs传递给方法本身。 However, I'd kind of like to be able to access the parameters within just the class itself, as there is some data I grab from an API that will be used in different capacities in different methods throughout the class. 但是,我有点想能够在类本身中访问参数,因为我从API中获取了一些数据,这些数据将在整个类中以不同的方式用于不同的容量。 Is there any way to do this? 有没有办法做到这一点?

You can do self.kwargs in any method that you use that is run after dispatch() is called for the class based view. 您可以在为基于类的视图调用dispatch()之后运行的任何方法中执行self.kwargs

If you are doing a detail view for a model, like it seems you are doing, you should probably use one of the generic class based views which will do this for you. 如果你正在为一个模型做一个详细视图,就好像你正在做的那样,你应该使用一个基于泛型类的视图来为你做这个。

Why don't you try the following: 你为什么不尝试以下方法:

from django.views.generic import DetailView

class LocationView(DetailView):
  queryset = LocationModel.objects.all()
  template_name = 'location_of_detail_template.html'

Then update your urls.py file and change the name of the regex group from id to pk to make it all work automatically. 然后更新您的urls.py文件并将正则表达式组的名称从id更改为pk,以使其全部自动运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM