i'm totally new to django and python. I would like to add a search bar working on my Listview page as I've seen on the Django admin-site.
I've seen a lot of django docs, many explainations and plenty of tutorials on the web but i have to say that I'm confused and could not find a solution for my problem. What i want to do: I have a page with a (class-based)ListView that presents 5 fields from my table. I would like to add a search bar working on 2 of these 5 fields (object id and description) as i've seen on the Django admin-site.
Looking at the Docs and web these are a lot of different propositions to do that(queryset, filter, context, Q...). Personally I would like to work with the context. I tried to recover info from my searchbar but what I have implemented and tried since now is not working. Could someone help me on this matter? What is the best practice and approach? Indications on how to manage this with some code exemple? Thanks in advance!
#HTML
<form method="GET">
<input type="text" name="q" value="" id="searchbar" autofocus>
<input class="button" type="submit" value="Search">
</form>
#View class AircraftListView(ListView):
model = Aircraft
paginate_by = 10
def get_context_data(self, **kwargs):
context = super(AircraftListView, self).get_context_data(**kwargs)
print(context)
filter_set = Aircraft.objects.all()
if self.request.GET.get('searchbar'):
q = self.request.GET.get('searchbar')
print('Hello I am on the right way')
filter_set = filter_set.filter(q=self.aircraft.air_tailnumber)
else:
print('I took the wrong way')
return context
CodePudding user response:
Since you don't want to use django filter, I will try to give an example for your view. Instead of overriding get_context_data
which is for extra context actually, override get_queryset
method in your ListView
. something like:
def get_queryset(self):
queryset = super().get_queryset()
search_text = request.GET.get("searchbar")
if search_text:
return queryset.filter(your_model_field=search_text)
return queryset