简体   繁体   中英

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 all of the values matching 41. I have come accross a few ways of doing this with function based views, but not class based Django views.

I have tried:

views.py

class DefaultsListView(LoginRequiredMixin,ListView):
    model = models.DefaultDMLSProcessParams
    template_name = 'defaults_list.html'
    login_url = 'login'
    def get_queryset(self):
        return models.DefaultDMLSProcessParams.objects.filter(device=self.kwargs[device])

urls.py

path('<int:device>', DefaultsListView.as_view(), name='Default_Listview'),

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:

class DefaultsListView(LoginRequiredMixin,ListView):
    model = models.DefaultDMLSProcessParams
    template_name = 'defaults_list.html'
    login_url = 'login'

    def get_queryset(self):
        return models.DefaultDMLSProcessParams.objects.filter(
            device=self.kwargs[]
        )

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:

class DefaultsListView(LoginRequiredMixin,ListView):
    model = models.DefaultDMLSProcessParams
    template_name = 'defaults_list.html'
    login_url = 'login'

    def get_queryset(self):
        return super(DefaultsListView, self).filter(
            device_id=self.kwargs['device']
        )

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