Dynamically filter ListView CBV in Django 1.7 Dynamically filter ListView CBV in Django 1.7 django django

Dynamically filter ListView CBV in Django 1.7


First of all you need to change your urls.py so that it'll pass the experience as a parameter. Something like this:

urlpatterns = patterns('',    url(r'^(?P<exp>[ASG])$', ScholarshipDirectoryView.as_view(), name='scholarship_directory'),)

(the above will return 404 if /A or /S or /G is not passed)

Now, in kwargs attribute of the CBV we will have a kwarg named exp which can be used by the get_queryset method to filter by experience level.

class ScholarshipDirectoryView(ListView):    model = Scholarship    template_name = 'scholarship-directory.html'    def get_queryset(self):        qs = super(ScholarshipDirectoryView, self).get_queryset()        return qs.filter(experience_level__exact=self.kwargs['exp'])