Python Django搜索函数
如何在django中提供搜索栏?我的代码如下 home.htmlPython Django搜索函数,python,html,django,web,Python,Html,Django,Web,如何在django中提供搜索栏?我的代码如下 home.html <form method='GET' action=""> <input type="text" name="search" placeholder="Search posts"/> <input type="submit" value="Search"/> </form> 您可能需要基于函数的视图。这可能是一个重复的或半相关的问题 from django.shortcuts i
<form method='GET' action="">
<input type="text" name="search" placeholder="Search posts"/>
<input type="submit" value="Search"/>
</form>
您可能需要基于函数的视图。这可能是一个重复的或半相关的问题
from django.shortcuts import render
from django.db.models import Q
from .models import Posts #or whatever your model is
def search(request):
query = request.GET.get('q','')
#The empty string handles an empty "request"
if query:
queryset = (Q(text__icontains=query))
#I assume "text" is a field in your model
#i.e., text = model.TextField()
#Use | if searching multiple fields, i.e.,
#queryset = (Q(text__icontains=query))|(Q(other__icontains=query))
results = Posts.objects.filter(queryset).distinct()
else:
results = []
return render(request, 'home.html', {'results':results, 'query':query})
#You can also set context = {'results':results, 'query':query} after
#the else: (same indentation as return statement), and
#use render(request, 'home.html', context) if you prefer.
您应该能够根据需要提出自己的错误处理或重定向。您的URL.py可能必须是:
from django.urls import path
from . import views
urlpatterns = [
path('feed/', views.search, name='home'),
#'feed/' being the name of desired url, 'views.search' the
#name of your func-based view, and "name='home'" the template
#you're using.
]
{% if query %}
{% if results %}
<ul>
{% for item in results %}
<li>{{ item|escape }}</li>
{% endfor %}
</ul>
{% else %}
<p>Query returned no results.</p>
#SO is formatting "Query" in HTML for some reason. Nonetheless...
{% endif %}
{% endif %}
您的搜索栏可能需要如下所示:
<form method='GET' action=".">
#I believe lowercase get also works
<input type="text" name="q" placeholder="Search posts"/>
<input type="submit" value="{{ query|escape }}"/>
</form>
#我相信小写的get也能起作用
编辑:我忘了你想访问结果并在模板中显示它们(你现在可以把它放在表单下)。比如:
from django.urls import path
from . import views
urlpatterns = [
path('feed/', views.search, name='home'),
#'feed/' being the name of desired url, 'views.search' the
#name of your func-based view, and "name='home'" the template
#you're using.
]
{% if query %}
{% if results %}
<ul>
{% for item in results %}
<li>{{ item|escape }}</li>
{% endfor %}
</ul>
{% else %}
<p>Query returned no results.</p>
#SO is formatting "Query" in HTML for some reason. Nonetheless...
{% endif %}
{% endif %}
{%if查询%}
{%if结果%}
{results%%中的项的%s}
- {{item | escape}}
{%endfor%}
{%else%}
查询未返回任何结果
#出于某种原因,在HTML中格式化“查询”也是如此。尽管如此。。。
{%endif%}
{%endif%}
搜索栏?我想这取决于你如何用css/js的东西来设计它