I am working on a blog site where you can search for posts by using searching with keywords (basically a normal searchbar).
I have imported Q from django.db.models
The view I created:
def search(request):
queryset = Article.objects.all()
query = request.GET.get('q')
if query:
queryset = queryset.filter(
Q(title__icontains=query) |
Q(overview__icontains=query)
).distinct()
context = {
'queryset': queryset,
}
return render(request, 'search_results.html', context)
The urlpattern:
path('search/', search, name='search-results'),
The form itself:
<form action="{% url 'search' %}" class="search-form">{% csrf_token %}
<button type="submit" class="submit"><i class="icon-search"></i></button>
<div class="form-group">
<span class="icon icon-search"></span>
<input type="text" class="form-control" name="q" placeholder="Type a keyword and hit enter">
</div>
</form>
When I want to access the page to which I have put this form in, it says: Reverse for 'search' not found. 'search' is not a valid view function or pattern name.
Below it also shows this:
1 <!DOCTYPE html>
2 <html lang="en">
3
4 {% include 'head.html' %}
5
6 <body>
7
8 {% include 'header.html' %}
9
10 {% block content %}
I have tried adding/removing csrf_token and the submit button, but the result is always the same. Please help!
I assume the form is a part of the head.html
. You don't need the csrf_token
since it's not a post
form.
In urlpatterns
, change your url entry to:
path('search/', views.search, name='search'),
At the template, action="{% url 'search' %}"
refers to the name of the url ... you could also add role='search'
attribute to your form. Hope it helps