I’m trying to filter ListView
based on post method from search bar in my base
template. So making it works like:
Insert name --> SearchBar-->GET Method-->SearchView class(in views.py)--> render html with usernames.
I have done this, but it wont work. Could you please tell me what I’m doing wrong?
views.py in my user app
class SearchView(ListView): model = User template_name = 'blog/list_of_users.html' context_object_name = 'all_search_results' def get_queryset(self): result = super(SearchView, self).get_queryset() query = self.request.GET.get('search') if query: postresult = User.objects.filter(username__contains=query) result = postresult else: result = None return result
urls.py in my blog
app
path('users_search/?search=<str:username>', user_view.SearchView.as_view(), name='user_search'),
search form in html
<form class="example" method="GET"> <input type="search" placeholder="ユーザー検索..." name="user_name"> <button type="submit"> 検索 </button>
rendered html with user names
{% for result in all_search_results %} {{ result.username }} {% empty %} add something to show no results {% endfor %}
Advertisement
Answer
override get_context_data
method
def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user_name = self.request.GET.get('user_name', '') context['all_search_results'] = User.objects.filter(username__icontains=user_name ) return context
In your template
<form class="example" method="GET"> <input type="text" placeholder="ユーザー検索..." name="user_name"> <button type="submit"> 検索 </button> </form> {% for result in all_search_results %} {{ result.username }} {% empty %} add something to show no results {% endfor %}
Update:
in template
, <input ........... name="search">
in views
, user_name = self.request.GET.get('search', '')