Win*_*hoo 0 python django django-forms django-views
我目前正在使用表单进行搜索
这是我的views.py
class HomeView(generic.ListView):
model = Consultant
template_name = 'sogeti/home.html'
def get_queryset(self):
query = self.request.GET.get('q')
if query:
return Consultant.objects.filter(
Q(first_name__icontains=query) |
Q(last_name__icontains=query) |
Q(group__title_techGroup__contains=query) |
Q(practices__title_practice__contains=query)
)
else:
return Consultant.objects.all()
Run Code Online (Sandbox Code Playgroud)
这是我的 home.html
<form action="" method="get" class="form-inline">
<input type="text" name="q" placeholder="Enter Keyword" value="{{ request.GET.q }}" class="form-control">
<select name="filter" class="form-control">
<option value="all">All</option>
<option value="people">People</option>
<option value="certification">Certification</option>
<option value="skillset">Skillset</option>
</select>
<input type="submit" value="Search" class="btn btn-default">
</form>
<ol style="padding-left: 15px">
{% for consultant in object_list %}
<li>
<a href="{% url 'sogeti:detail' consultant.id %}">{{ consultant.first_name }}, {{ consultant.last_name }}</a> </br>
Technology Group: {{ consultant.group }} </br>
Primary Practice: {{ consultant.practices }}
<hr style="margin-left: 0">
</li>
{% endfor %}
</ol>
Run Code Online (Sandbox Code Playgroud)
我的第一个问题是,当它尝试搜索不在我的数据库中的内容(例如:bla)时,它会返回空白屏幕。什么都没有。尝试搜索但无法得到任何答案。
我的第二个问题是如何使用 HTML 选择和过滤选项来指定我的搜索。正如您从我的 home.html 中看到的,我有带有选项值的标签,但不知道如何将它用于 Django。
非常感谢你的帮助!真的很欣赏它。
关于第一个问题,您实际上可以object_list在迭代之前仔细检查它,例如:
{% if object_list %}
<ul>
{% for item in object_list %}
<p>{{item.value}}</p>
{% endfor %}
</ul>
{% else %}
<p>Empty!</p>
{% endif %}
Run Code Online (Sandbox Code Playgroud)
如果您无法搜索,请使用一些工具(例如django-debug-toolbar查看查询)仔细检查您的查询。
关于第二个问题,我建议您使用 Django Form 代替,如下所示: Create forms.py:
from django.forms import Form, ChoiceField, CharField
class FilterForm(Form):
FILTER_CHOICES = (
('all', 'All'),
('people', 'People'),
('certification', 'Certification'),
('skillset', 'Skillset'),
)
search = CharField(required=False)
filter_field = ChoiceField(choices=FILTER_CHOICES)
Run Code Online (Sandbox Code Playgroud)
那么你的看法(views.py):
class HomeView(ListView):
model = Consultant
template_name = 'home.html'
def get_queryset(self):
query = self.request.GET.get('search')
filter_field = self.request.GET.get('filter_field')
# Do your filter and search here
return Consultant.objects.all()
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['form'] = FilterForm(initial={
'search': self.request.GET.get('search', ''),
'filter_field': self.request.GET.get('filter_field', ''),
})
return context
Run Code Online (Sandbox Code Playgroud)
最后是您的模板 ( templates/home.html):
<form class="row">
{{ form.search }}
{{ form.filter_field }}
<input type="submit" class="btn btn-default" value="Search">
</form>
Run Code Online (Sandbox Code Playgroud)
希望这会有所帮助!