I am trying to add search functionality to a ListView in two places in my Django application. From the homepage, I want users to be able to filter by zip code, and on the ListView template, I also want users to have the ability to filter by another attribute in the model. My issue is that the self.request.GET.get('q') returns None when filtering from the ListView page, and I want it to retain the zip code filter that I used in the previous page.
For search functionality, I am using Q.
How can I retain the zip code filter from the initial request so that I can query on both zip code and category?
views.py
class ListingsView(ListView):
model = Listing
template_name = 'listings/list.html'
context_object_name = 'listing_list'
def get_queryset(self):
query_zip = self.request.GET.get('q_zip_code')
query_category = self.request.GET.get('q_category')
if query_category == None:
queryset = Listing.objects.filter(Q(zip_code__icontains = query_zip))
else:
queryset = Listing.objects.filter(Q(zip_code__icontains = query_zip) & Q(category__icontains = query_category))
return queryset
home.html
<p>
<form action="{% url 'rental_listings_list' %}" method="get">
<input name="q_zip_code" type="text" placeholder="Zip Code" aria-label="Zip Code">
<button type="submit">SEARCH</button>
</form>
</p>
list.html
<form action="{% url 'rental_listings_list' %}" method="get">
<input name="q_category" type="text" placeholder="Category" aria-label="Category">
<button type="submit">UPDATE</button>
</form>
CodePudding user response:
Add in your list.html
:
action="{% url 'rental_listings_list' %}?q_category={{ request.GET.q_category }}"
CodePudding user response:
Finally figured it out with help from Maxim!
Add to list.html
<input name="q_zip_code" type="hidden" value="{{ request.GET.q_zip_code }}">
Add to view.py
def get_queryset(self):
query_zip = self.request.GET.get('q_zip_code')
query_category = self.request.GET.get('q_category')
if query_category == None:
queryset = RentalListing.objects.filter(Q(zip_code__icontains = query_zip))
else:
query_zip = self.request.GET.get('q_zip_code', '')
queryset = RentalListing.objects.filter(Q(zip_code__icontains = query_zip) & Q(category__icontains = query_category))
return queryset