Django ListView customising queryset

前端 未结 2 679
无人共我
无人共我 2020-12-17 14:31

Hopefully this should be a simple one to help me with.

I have a page with a dropdown menu containing three items:

&l
2条回答
  •  青春惊慌失措
    2020-12-17 15:03

    To solve this problem I just modified the pagination HTML, to accommodate both the get request from the form and the page number in the url string, like so:

    
    

    The {{ input }} here is a string containing the option submitted via the form, e.g. 'Cats' or 'Worms'.

    To be able to pass this into the template, I modified the get_context_data method of the class based view as such:

    class Browse(generic.ListView):
        template_name = 'app/browse.html'
        paginate_by = 25
    
        # Modifying the get_context_data method
    
        def get_context_data(self, **kwargs):
            context = super(Browse, self).get_context_data(**kwargs)
            q = self.request.GET.get("browse")
            context['input'] = q
            return context
    
        def get_queryset(self):
            queryset = Cats.objects.all()
            if self.request.GET.get("browse"):
                selection = self.request.GET.get("browse")
                if selection == "Cats":
                    queryset = Cats.objects.all()
                elif selection == "Dogs":
                    queryset = Dogs.objects.all()
                elif selection == "Worms":
                    queryset = Worms.objects.all()
                else:
                    queryset = Cats.objects.all()
            return queryset
    

    That was it, the url string now reads something like:

    /browse/?browse=Cats&page=3
    

    So there it is, pagination now works alongside the get method of the form.

提交回复
热议问题