django搜索框功能的实现
时间: 2023-06-10 16:07:30 浏览: 102
Django 搜索框功能的实现需要以下步骤:
1. 安装 Django 搜索模块:`pip install django-haystack`
2. 在 settings.py 文件中添加以下配置:
```python
INSTALLED_APPS = [
# ...
'haystack',
]
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
},
}
HAYSTACK_SIGNAL_PROCESSOR = 'haystack.signals.RealtimeSignalProcessor'
```
3. 创建搜索索引类,例如在 app 目录下创建 search_indexes.py 文件,添加以下代码:
```python
from haystack import indexes
from .models import Post
class PostIndex(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
publish = indexes.DateTimeField(model_attr='publish')
def get_model(self):
return Post
def index_queryset(self, using=None):
return self.get_model().published.all()
```
4. 在 app 目录下创建 templates/search/indexes/app/post_text.txt 文件,添加以下代码:
```html
{{ object.title }}
{{ object.body }}
```
5. 在 app 目录下创建 views.py 文件,添加以下代码:
```python
from django.views.generic import ListView
from haystack.generic_views import SearchView
from .models import Post
class PostListView(ListView):
model = Post
queryset = Post.published.all()
context_object_name = 'posts'
paginate_by = 3
template_name = 'blog/post/list.html'
class PostSearchView(SearchView):
template_name = 'blog/post/search.html'
```
6. 在 app 目录下创建 urls.py 文件,添加以下代码:
```python
from django.urls import path
from .views import PostListView, PostSearchView
urlpatterns = [
path('', PostListView.as_view(), name='post_list'),
path('search/', PostSearchView.as_view(), name='post_search'),
]
```
7. 在 templates 目录下创建 blog/post/search.html 模板文件,添加以下代码:
```html
{% extends 'base.html' %}
{% block content %}
<h1>Search Posts</h1>
{% if query %}
<h2>Results for "{{ query }}"</h2>
<ul>
{% for result in page_object %}
<li>
<a href="{{ result.object.get_absolute_url }}">{{ result.object.title }}</a>
<p>{{ result.object.body|safe }}</p>
</li>
{% empty %}
<li>No results found.</li>
{% endfor %}
</ul>
{% else %}
<p>Enter a search query above.</p>
{% endif %}
{% endblock %}
```
8. 在搜索框视图中添加搜索引擎的配置信息,例如:
```python
class PostSearchView(SearchView):
template_name = 'blog/post/search.html'
queryset = Post.objects.all()
def get_context_data(self, *args, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(*args, **kwargs)
# Add in a QuerySet of all the books
context['posts'] = self.queryset
return context
def get_queryset(self):
queryset = super().get_queryset()
q = self.request.GET.get('q')
if q:
queryset = queryset.filter(title__icontains=q)
return queryset
```
9. 在模板文件中添加搜索框,并设置其 action 属性为搜索视图的 URL:
```html
<form action="{% url 'post_search' %}" method="get">
<input type="text" name="q">
<input type="submit" value="Search">
</form>
```
以上就是 Django 搜索框功能的实现步骤。
阅读全文