Django搜索功能

时间:2018-11-18 20:03:05

标签: 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>

views.py

def home(request):
posts = Post.objects.all()
search_term = ''

if 'search' in request.GET:
    search_term = request.GET['search']
    posts = posts.filter(text__icontains=search_term)

context = {
    'posts': posts,
    'search-term': search_term
}

return render(request, 'feed/home.html', context)

1 个答案:

答案 0 :(得分:1)

您可能需要基于功能的视图。这可能是重复或半相关的问题。

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. 

您应该能够根据需要进行自己的错误处理或重定向。您的urls.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.
]

您的搜索栏可能看起来像:

<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>

编辑:我忘记了您想要访问结果并将其显示在模板中(您现在可以将其放在表单下)。像这样:

{% 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 %}