gpt4 book ai didi

python - Django 搜索表单返回整个模型

转载 作者:行者123 更新时间:2023-12-01 01:07:48 24 4
gpt4 key购买 nike

我正在尝试使用 Django 为基于类的 View 创建一个简单的搜索表单。一切似乎都有效,除了搜索结果返回整个模型,所以显然搜索/过滤器不起作用。在阅读了这里的一堆教程和问题后,我无法弄清楚为什么。

models.py:

class surveys(models.Model):
FAN = models.SlugField(max_length=100, blank=True, null=True)
Location = models.CharField(max_length=200, blank=True, null=True)

def __str__(self):
return self.FAN

def get_absolute_url(self):
return reverse('survey-detail', args=[str(self.FAN)])

views.py:

class Search(generic.ListView):
template_name = 'datalibrary/search.html'
model = surveys

def get_queryset(self):
try:
name = self.kwargs['name']
except:
name = ''
if (name != ''):
object_list = self.model.objects.filter(FAN__icontains == name)
else:
object_list = ''
return object_list

class SearchResults(generic.ListView):
template_name = 'datalibrary/search_results.html'
model = surveys

search.html:

{% extends "base_generic.html" %}

{% block content %}
<form method="get" action="/results/" class="navbar-form pull-right">
<input type="text" id="searchBox" class="input-medium search-query" name="search" placeholder="Search">
<input type="submit" class="btn" value="Search" >
</form>
{% endblock %}

search_results.html:

{% extends "base_generic.html" %}

{% block content %}
{{ object_list }}
{% endblock %}

urls.py:

urlpatterns +=[
path('search/', views.Search.as_view(), name='search'),
path('results/', views.SearchResults.as_view(), name='search-results'),
]

知道为什么 object_list 返回模型中的所有值,而不是根据输入进行过滤,即使没有输入也是如此?

最佳答案

你有name = self.kwargs['name'],它没有得到任何'name',对于搜索来说,更好的方法是将输入的名称作为查询并显示结果。

class Search(generic.ListView):
template_name = 'datalibrary/search.html'
context_object_name = 'all_search_results'

def get_queryset(self):
result = super(Search, self).get_queryset()
query = self.request.GET.get('search') #your input name is 'search'

if query:
object_list = surveys.objects.filter(FAN__icontains=query) #or FAN__contains
result = object_list
else:
result = None # When no result found

return result

在 HTML 中,

{% extends "base_generic.html" %}

{% block content %}
<form method="get" action="/results/" class="navbar-form pull-right">
<input type="text" id="searchBox" class="input-medium search-query" name="search" placeholder="Search">
<input type="submit" class="btn" value="Search" >
</form>



{% for result in all_search_results %}
{{result.add_according_to_the_model}}
{% empty %}
<p> No Results <p>
{% endfor %}

{% endblock %}

您可以在同一页面中显示搜索结果。但是,如果您需要,那么您可以使用不同的 html。

关于python - Django 搜索表单返回整个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55172571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com