Get GET url parameters in class-base views for Django 3.2

Viewed 552

I found a similar question, but it was for Django 1.5, and I don't think it worked for me.

class SearchedPostListView(ListView):
    model = Post
    template_name = 'blog/search.html'  # <app>/<model>_<viewtype>.html
    paginate_by = 2
    context_object_name = 'posts'   

    def get_context_data(self, *args, **kwargs):
        context = super(SearchedPostListView, self).get_context_data(*args, **kwargs)
        query = self.kwargs.get('q')
        context['posts'] = Post.objects.filter(Q(title__icontains=query) | Q(author__username__icontains=query) | Q(content__icontains=query))
        context['categories'] = Categories.objects.all
        return context

This is my code. I am trying to search through all the posts on my website, and I'm showing any posts that have the query in the title.

So, if I type in the URL localhost:8000/search?q=foo, then it has to show me the posts that contain the word foo in its title.

But I'm not able to access the GET parameters. How do I access the GET parameters in Django 3.2?

1 Answers

Use query = self.request.GET.get('q') instead query = self.kwargs.get('q').

    class SearchedPostListView(ListView):
        model = Post
        template_name = 'blog/search.html'  # /_.html
        paginate_by = 2
        context_object_name = 'posts'   
    
        def get_context_data(self, *args, **kwargs):
            context = super(SearchedPostListView, self).get_context_data(*args, **kwargs)
            query = self.request.GET.get('q')
            context['posts'] = Post.objects.filter(Q(title__icontains=query) | Q(author__username__icontains=query) | Q(content__icontains=query))
            context['categories'] = Categories.objects.all
            return context
Related