问题
I want to integrate elastic search with django but first I need to get a nice parameter in url
http://127.0.0.1:8000/search?q=search+term
urls.py (of the view)
urlpatterns = [
path('?q=', SearchIndexView.as_view(), name="search-index"),
]
urls.py (of the app)
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('home.urls')),
path('u/', include('user.urls')),
path('search', include('search.urls')),
]
That is what I have so far but I cant figure out how to make it work. I want to use tha path() and not url() if possible
回答1:
You don't need to define url query strings in urls.py
. You can keep the url like this:
path('', SearchIndexView.as_view(), name="search-index"),
and in SearchIndexView
you can do it like this:
q = request.GET.get('q')
回答2:
keep your url like this
urlpatterns = [
path('', SearchIndexView.as_view(), name="search-index"),
]
in the html form
<form method='GET'>
and in the input put name="q"
回答3:
HTML FORM
<form action="{%url 'search' %}" method="get">
<input type="text" name="q" placeholder="Search...">
<button type="submit"></button>
</form>
urls
path('search/',views.search,name='search')
views
def search(request):
query = request.GET.get('q')
if query:
print("do your stuff here")
回答4:
in Django generic views you can create search views as follows for model Blog
class SearchResultView(ClientMixin, TemplateView):
template_name = 'clienttemplates/clientsearchresult.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
query = self.request.GET.get('q')
if query:
lookup = Q(title__icontains=query)
search_list = Blog.objects.filter(lookup)
context["slist"] = searchlist
return context
in html simply put name='q' inside input tag
<input type="text" class="search-field " placeholder="Search Blog..." value="" name='q'>
in urls.py
path('search/result', SearchResultView.as_view(), name="searchresult"),
in clientsearchresult.html you can simply add
{% if slist %}
{% for blog in slist %}
{{blog.title|title}}
{{bog.content|safe}}
{% endfor %}... and so on
{% endif %}
来源:https://stackoverflow.com/questions/53920004/add-q-searchterm-in-django-url