user8733268
user8733268

Reputation:

Django: Search Function If No Initial Data

def search(request):
    query = request.GET.get('q')
    ....
    ....
    return render(request, 'search.html', {'list': list})

form looks like this,

<form method="get" action="{% url 'new:search' %}">
   <input type="text" name="q" value="{{ request.GET.q }}">
   <input type="submit" value="Search" />
</form>

Everything is working fine here but if a user simply press the "Search" button it shows all data instead of doing nothing.

So, how can I make this search function do nothing when user directly press the Search button without entering initial data?

Upvotes: 2

Views: 104

Answers (1)

markwalker_
markwalker_

Reputation: 12869

Based on the function you've provided, list must be "all the data" and therefore you need to return without that.

def search(request):
    q = request.GET.get('q', None)
    if not q:
        return render(request, 'search.html', {'list': []})
    else:
        ....
    return render(request, 'search.html', {'list': list})

Upvotes: 1

Related Questions