Issue
While trying to create a simple search form using method="POST" and action linking to a url that should trigger a view to render a different template I have come across it not working all it does is tag on the csrf to my index url and acts like I am using GET not POST any thoughts on why?
HTML URL:
http://127.0.0.1:8000/bugtracker/?csrfmiddlewaretoken=jdGcvGb8pioQutLhDOL8y6zbK7DW6XSErTYQ8zHOI8W1fAXf8V6NFoFmzXRIvC3d&searched=
View:
@login_required(login_url='login_register')
def search_site(request):
if request.method == "POST":
searched = request.POST['searched']
context = {
'searched': searched
}
return render(request, 'bugs/search_site.html', context)
else:
return render(request, 'bugs/search_site.html')
URL:
path('search_site/', views.search_site, name='search_site'),
Search bar template:
<div class="input-group">
<form method="POST" action="{% url 'search_site' %}">
{% csrf_token %}
<input class="form-control" type="search" placeholder="Search for..." aria-label="Search for..." name="searched">
<button class="btn btn-primary" type="submit"><i class="fas fa-search"></i></button>
</form>
</div>
Search result template:
{% extends 'bugs/base.html' %}
{% block content %}
<div class="container-fluid px-4">
{% if searched %}
<h4 class="mt-4">results for {{ searched }}</h4>
{% endif %}
</div>
{% endblock %}
I have tried changing method to get, I have tried to change my url and my view to no avail. and removing crf just makes the url tag a ? into the index it seems like it is not calling anything at all.
Solution
I can provide two suggestions, first to render outside the else condition, and the second to see searched
has any value or not by printing it.
@login_required(login_url='login_register')
def search_site(request):
if request.method == "POST":
searched = request.POST['searched']
print(f"searched value --> {searched}")
context = {
'searched': searched
}
return render(request, 'bugs/search_site.html', context)
return render(request, 'bugs/search_site.html')
Search result template:
{% extends 'bugs/base.html' %}
{% block content %}
<div class="container-fluid px-4">
{% if searched %}
<h4 class="mt-4">results for {{ searched }}</h4>
{% else %}
<p>No value has come.</p>
{% endif %}
</div>
{% endblock %}
I also think it should be another template in POST
Method check it, you have provided search_site.html
may be it is something like search_result.html
.
Answered By - Sunderam Dubey
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.