我正在尝试做一个基本的搜索功能,但我遇到了一个小问题。当我转到具有搜索表单的模板时,它会在我尝试搜索之前显示所有项目。有没有办法显示空白模板,直到用户输入搜索词并点击搜索按钮?
示例:
[搜索字段] [按钮]
1
2
3
等等
views.py
def view_player_home(request):
if request.method == 'GET':
form = searchPlayerForm(request.GET)
if form.is_valid():
string = form.cleaned_data.get('text')
players = Player.objects.filter(Q(first_name__icontains = string)|Q(last_name__icontains = string))
return render_to_response('player/player.html', {'form': form, 'players':players}, context_instance=RequestContext(request))
else:
form = searchPlayerForm()
return render_to_response('player/player.html', {'form': form}, context_instance=RequestContext(request))
forms.py
class searchPlayerForm(forms.Form):
text = forms.CharField(label = "Search")
def __init__(self, *args, **kwargs):
super(searchPlayerForm, self).__init__(*args, **kwargs)
self.fields['text'].required = False
模板
{% extends "base.html" %}
{% block content %}
<h5>Find Player</h5>
<form method="GET" action="">
{% csrf_token %}
{{ form.as_table }}
<input type="submit" value="Submit"/>
</form>
{% if players %}
{% for p in players %}
{{ p.first_name }} {{ p.last_name }}
{% endfor %}
{% else %}
No Players
{% endif %}
{% endblock %}
答案 0 :(得分:1)
应该做一个改变:
if request.method == 'GET':
应该是
if request.GET:
潜在的问题是你的请求方法总是GET,所以你永远不会进入else块或函数的底部。
答案 1 :(得分:1)
另一种选择是在GET数据中明确查找一个术语
if request.GET and 'text' in request.GET:
# do query / processing
甚至不允许空白
if request.GET and 'text' in request.GET and request.GET['text'] != '':
# do query / processing
如果您只有一个字段或正在检查表单中的选项是否具有特定值,则此工作很容易。
在做很多字段时,我喜欢做一个命名的提交按钮,这样我就可以检查它是否被点击,然后按if语句检查按钮名称。