Reputation: 23713
I have a search page where user can submit queries that try to match objects in a database. When the user has submitted the form and no results have been found for his/her query, I want to give the message "No results found for this query". The problem I'm having now is that the message is shown even when the user has not submitted the form yet.
This is what my code looks like:
Review Template
<div> What do you want to review? </div>
<form action="/newreview/" method="get">
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }}: {{ field }}
</div>
{% endfor %}
<input type="submit" value="Submit" name="submit" />
{% if results %}
{{ results.id }}
{% else %}
<li> There is no results for this search </li>
{% endif %}
</form>
And I do the following for the View:
def newreview(request):
if 'submit' in request.GET: # If the form has been submitted...
form = LookforPlace(request.GET) # A form bound to the GET data
if form.is_valid(): # All validation rules pass
name = form.cleaned_data['name']
city = form.cleaned_data['city']
try:
results = Place.objects.get(name__icontains=name)
except Place.DoesNotExist:
results = None
else:
results = []
form = LookforPlace() # An unbound form
return render_to_response('newreview.html', {
'form': form, 'results': results,
})
I thought that by doing the conditional on the results list, I could check whether the form has been submitted or not (empty list from the view).
Right now this code is giving me "There is no results for this search" even if there has not been any submission. Any thoughts?
Upvotes: 0
Views: 564
Reputation: 599846
Why not put a flag in your context to determine whether or not it has been submitted?
if 'submit' in request.GET:
submitted = True
...
else:
submitted = False
...
{% if submitted %}
{% if results %}
{{ results.id }}
{% else %}
<li> There are no results for this search </li>
{% endif %}
{% endif %}
Upvotes: 1