How to pass variable in url to Django List View

扶醉桌前 提交于 2021-01-28 03:51:02

问题


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'),

回答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:

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_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:

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

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


来源:https://stackoverflow.com/questions/52871149/how-to-pass-variable-in-url-to-django-list-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!