简体   繁体   中英

Best Way to get kwargs in a class based view?

I have a class based Django view:

class LocationView(TemplateView):

I have defined a named parameter in my url dispatcher:

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. 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. 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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