[Django]-Set form input as variable in get_queryset

3👍

In get_context_data you don’t use get_queryset method at all. You just write another query which fetch all Hashtag objects. You should rewrite it to this:

def get_context_data(self, **kwargs):
    context = super(SearchResultsView, self).get_context_data(**kwargs)
    context['search_text'] = self.get_queryset()
    return context

Note self.get_queryset() is using instead of Hashtag.objects.all().

Also note to use self.request.GET.get('search_text') you need to pass search_text as GET argument when performing redirect in HashtagSearch view:

class HashtagSearch(FormView):
    """ FormView for user to enter hashtag search query """

    template_name = 'mapping_twitter/hashtag_search_form.html'
    form_class = SearchHashtagForm

    def get_success_url(self):
        return '{}?search_text={}'.format(reverse('mapping_twitter:results'),  self.request.POST.get('search_text'))

UPD

But isntead of two views I recommend you to use single ListView. Just add GET form to your results.html and simple override get_queryset method:

# template 
<form method="GET" action="">
      <input type="text"  name="search_text" placeholder="Search post" value="{{ request.GET.search_text }}">
      <input type="submit" value="Search">
</form>


# view
class SearchResultsView(generic.ListView):
    """ Generic class-based view listing search results of locations """
    model = Hashtag
    template_name = 'mapping_twitter/results.html'

    def get_queryset(self, **kwargs):

        # ISSUE: restrict the search_text displayed on results.html to the 'search_text' entered by the user
        qs = Hashtag.objects.all()

        form_input = self.request.GET.get('search_text')

        if form_input:
            qs = qs.filter(search_text__iexact=form_input)

        return qs

Leave a comment