7

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 Answer 1

15

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']
        )
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.