How To Pass Variable In Url To Django List View
I have a Django generic List View that I want to filter based on the value entered into the URL. For example, when someone enters mysite.com/defaults/41 I want the view to filter
Solution 1:
You are close, the self.kwargs
is a dictionary that maps strings to the corresponding value extracted from the URL, so you need to use a string that contains 'device'
here:
classDefaultsListView(LoginRequiredMixin,ListView):
model = models.DefaultDMLSProcessParams
template_name = 'defaults_list.html'
login_url = 'login'defget_queryset(self):
return models.DefaultDMLSProcessParams.objects.filter(
device_id=self.kwargs['device']
)
It is probably better to use devide_id
here, since then it is syntactically clear that we compare identifiers with identifiers.
It might also be more "idiomatic" to make a super()
call, such that if you later add mixins, these can "pre-process" the get_queryset
call:
classDefaultsListView(LoginRequiredMixin,ListView):
model = models.DefaultDMLSProcessParams
template_name = 'defaults_list.html'
login_url = 'login'defget_queryset(self):
returnsuper(DefaultsListView, self).get_queryset().filter(
device_id=self.kwargs['device']
)
Post a Comment for "How To Pass Variable In Url To Django List View"