How to Implement Django search functionality to search all models in Django is a complex task and requires custom code and configuration.
Steps require for implementing search functionality for all models are.
Method one
1. Install Required Libraries:
You’ll need to install the django-haystack package, which integrates with search engines like Elasticsearch, Solr, or Whoosh. You’ll also need a search engine itself. For this example, we’ll use Whoosh, a pure-Python search engine.
pip install django-haystack Whoosh
2. Configure Haystack in Django Settings:
Now you have Add ‘haystack’ to your INSTALLED_APPS and configure the search back-end. we’ll use Whoosh as i have said before :
# settings.py
INSTALLED_APPS = [
# ...
'haystack',
]
HAYSTACK_CONNECTIONS = {
'default': {
'ENGINE': 'haystack.backends.whoosh_backend.WhooshEngine',
'PATH': os.path.join(BASE_DIR, 'whoosh_index'),
},
}
3. Create Search Indexes for Models
For each model you want to include in the search, create a search index class in your app’s file. Define which fields should be indexed for searching.
# appname/search_indexes.py
<strong>from</strong> haystack <strong>import</strong> indexes
<strong>from</strong> .models <strong>import</strong> YourModel
<strong>class</strong> <strong>YourModelIndex</strong>(indexes.SearchIndex, indexes.Indexable):
text = indexes.CharField(document=True, use_template=True)
# Add other fields you want to index
<strong>def</strong> <strong>get_model</strong>(self):
<strong>return</strong> YourModel
<strong>def</strong> <strong>index_queryset</strong>(self, using=None):
<strong>return</strong> self.get_model().objects.all()
4. Create a Template for Search Results:
Create a template file (e.g., search/results.html) that will be used to display search results.
5. Create a Search View:
Create a view in your app’s views.py to handle search queries and render the search results template.
# appname/views.py
<strong>from</strong> django.shortcuts <strong>import</strong> render
<strong>from</strong> haystack.query <strong>import</strong> SearchQuerySet
<strong>def</strong> <strong>search</strong>(request):
query = request.GET.get('q', '')
<strong>if</strong> query:
results = SearchQuerySet().filter(content=query)
<strong>else</strong>:
results = []
<strong>return</strong> render(request, 'search/results.html', {'results': results, 'query': query})
6. Configure URLs:
Configure a URL pattern to map to the search view.
# appname/urls.py
<strong>from</strong> django.urls <strong>import</strong> path
<strong>from</strong> . <strong>import</strong> views
urlpatterns = [
# ... your other URL patterns ...
path('search/', views.search, name=search),
]
7. Create a Search Form (Optional):
<strong>class</strong> <strong>SearchForm</strong>(forms.Form):
search_query = forms.CharField(max_length=100)
You can create a search form using Django’s forms to handle search queries and display the search input field in your template.
8. Include the Search Form in Your Template:
Add the search form to your template, allowing users to enter search queries.
9. Run Migrations:
Create the database schema for Haystack’s search index by running:
python manage.py makemigrations
python manage.py migrate
10. Collect Static Files (for Whoosh):
If you’re using Whoosh, you’ll need to collect static files for the search index:
python manage.py collectstatic
11. Run the Development Server:
Method two
Create a html file then name it search_result.html then include the below codes inside of it.
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<<strong>div</strong> class="container">
<<strong>h1</strong>>Search Results</<strong>h1</strong>>
<<strong>form</strong> method="get" action="{% url 'search' %}">
{{ form | crispy }}
{{form.media}}
<<strong>p</strong>></<strong>p</strong>>
<<strong>button</strong> class="btn btn-secondary" id="submitBtn" type="submit">Search</<strong>button</strong>>
<<strong>a</strong> href="{{request.META.HTTP_REFERER}}" style="margin-left:10px;" class="btn btn-primary">Go Back</<strong>a</strong>>
</<strong>form</strong>>
{% if results %}
<<strong>h2</strong>>Results:</<strong>h2</strong>>
<<strong>ul</strong>>
{% for result in results %}
<<strong>li</strong>><<strong>a</strong> href="{{result.get_absolute_url}}">{{ result|safe }}</<strong>a</strong>></<strong>li</strong>>
<<strong>p</strong>>{{ result.content|safe|striptags|truncatechars:150 }}</<strong>p</strong>>
{% endfor %}
</<strong>ul</strong>>
{% else %}
<<strong>p</strong> class=""> No Result Found for the querry</<strong>p</strong>>
{% endif %}
</div
{% endblock %}
Now after creating this file you have to create a view function.
CREATE A SEARCH FORM
class SearchForm(forms.Form):
search_query = forms.CharField(max_length=100)
NOW CREATE THE VIEW FUNCTION MAKING SURE THAT YOUR SEARCH FORM IS INCLUDED
<strong>def</strong> <strong>search_view</strong>(request):
form = SearchForm(request.GET <strong>or</strong> None)
results = []
<strong>if</strong> form.is_valid():
search_query = form.cleaned_data['search_query']
# Search in Model1
blog_results = Blog.objects.filter(Q(title__icontains=search_query) | Q(content__icontains=search_query))
results.extend(blog_results)
# Search in Model2
article_results = Article.objects.filter(Q(content__icontains=search_query) | Q(title__icontains=search_query))
results.extend(article_results)
# Search in Model2
flutter_results = Flutter.objects.filter(Q(content__icontains=search_query) | Q(title__icontains=search_query))
results.extend(flutter_results)
# Search in Model2
brainy_results = Brainy.objects.filter(Q(content__icontains=search_query) | Q(title__icontains=search_query))
results.extend(brainy_results)
context = {
'results': results,
'form': form,
}
<strong>return</strong> render(request, 'search_results.html', context)
In the above method we have included many models as you can see follow the step and do your also.
Now you have to create a url mapping to map the view you have created.
path('search/', views.search_view, name='search'),
Now you are done visit the page and access the Django search functionality result via the first method or second method.
You can also read How To Redirect In Django Using Nginx Permanent Redirect
drop your comment below.