I'm creating a simple search application. I have a model with some data, and the index page is just a search bar that search results of that model. I'm creating the form using just HTML, not a proper Django Form.
index.html:
<form method="get" action="{% url 'core:search' %}?page=1&q={{ request.GET.q }}">
<div class="form-floating mb-3">
<input type="search" class="form-control" id="floatingInput" name="q" value="{{ request.GET.q }}">
<label for="floatingInput">Type your search</label>
</div>
<button class="w-100 btn btn-lg btn-primary" type="submit">Search</button>
</form>
The results are paginated, so I need that the url requested by the form is http://127.0.0.1:8000/search/?page=1&q=query
, query
being the search term typed in the input. But what I wrote in the action
parameter in the form doesn't work as I expected: even though it's writen action="{% url 'core:search' %}?page=1&q={{ request.GET.q }}
, the URL requested is just http://127.0.0.1:8000/search/?q=query
. The page
param simply doesn't show up.
I wrote page=1
because, as is the search result, the first one requested is always the first page.
The view that process this request is the search_view
. I'm putting it below just as more info, but I think the problem is my misunderstanding of url
template tag in the action
form parameter.
search_view:
def search_view(request):
posts = Post.objects.all()
query = request.GET.get('q')
page_num = request.GET.get('page')
paginator = Paginator(posts.annotate(
search=SearchVector('post_title', 'post_subtitle'),
).filter(search=query).order_by('post_title'), 15)
num_results = paginator.count
num_pages = paginator.num_pages
try:
posts = paginator.page(page_num)
except PageNotAnInteger:
posts = paginator.page(1)
except EmptyPage:
posts = paginator.page(paginator.num_pages)
context = {
'posts': posts,
'num_results': num_results,
'num_pages': num_pages,
'page_range': paginator.page_range,
}
return render(request, 'core/search.html', context)
How can I make the URL requested be like http://127.0.0.1:8000/search/?page=1&q=query
?