Search code examples
pythonhtmldjangosearchsearchbar

Making search bar in django


Im trying to make a search bar in django and watched several youtube totorials and none of those worked. What im trying to do is either make a search bar that redirects to articles/what_you_searched_for or if not possible show up results that include search. If someone has enough time they can tell me how to do both :). in views.py:

def index(request):
    queryset = article.objects.all()
    number_of_records = article.objects.count()
    random_page = random.randint(1,number_of_records)
    context = {
        "object_list": queryset,
        "random_page": random_page
    }

#    query = ""
#    if request.GET:
#        query = request.GET['q']
#        context['query'] = str(query)


    entries = util.list_entries()
    return render(request, "encyclopedia/index.html", context)
    #{
        #"entries": util.list_entries(),
        #"random_page": random_page,
    #})
def dynamic_articles_view(request, my_id):
    obj = article.objects.get(id= my_id)
    number_of_records = article.objects.count()
    random_page = random.randint(1,number_of_records)
    context = {
        "object": obj,
        "random_page": random_page
    }
    return render(request, "encyclopedia/article_detail.html", context)

in index.html:

{% extends "encyclopedia/layout.html" %}

{% block title %}
    Encyclopedia
{% endblock %}

{% block body %}
<h1 id="demo" onclick="add_article()">Article</h1>


    <ul>

        {% for instance in object_list %}
            <li><a href = "http://127.0.0.1:8000/articles/{{instance.id}}/">{{instance.title}}</a></li>
        {% endfor %}

    </ul>

{% endblock %}

layout.html: ------------ SEARCH BAR HERE ---------

{% load static %}
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>{% block title %}{% endblock %}</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
        <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet">
    </head>
    <body>
        <div class="row">
            <div class="sidebar col-lg-2 col-md-3">
                <h2>Wiki</h2>
                <form action = "/articles/{{q}}">                         __________EXACTLY HERE ________
                    <input class="search" type="text" name="q" placeholder="Search...">
                </form>
                <div>
                    <a href="{% url 'index' %}">Home</a>
                </div>
                <div>
                    <a href = "/new_article" >Create New Article</a>
                </div>
                <div>
                    <a href = "http://127.0.0.1:8000/articles/{{random_page}}">Random Page</a>
                </div>
                {% block nav %}
                {% endblock %}
            </div>
            <div class="main col-lg-10 col-md-9">
                {% block body %}
                {% endblock %}
            </div>
        </div>
    </body>
</html>

urls:

from django.contrib import admin
from django.urls import include, path
from encyclopedia import views
from encyclopedia.views import index, new_article, dynamic_articles_view
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include("encyclopedia.urls")),
    path('new_article/', new_article),
    path('home/', index, name = 'home'),
    path('articles/<int:my_id>/', dynamic_articles_view, name = 'articless')
]

encyclopedia urls (other folder):

from django.urls import path

from . import views

urlpatterns = [
    path("", views.index, name="index"),
    path("", views.new_article, name="new_article")
]

if needed i will comment models and forms but i dont want to make my question to long.


Solution

  • Simplest way is to add a GET form in your template with a search input without setting the action of the form:

    <form action="">
        <input type="text" name="search" placeholder="Search by title" value="{{request.GET.title}}">
        <input type="submit" value="Search">
    </form>
    

    Then in the views.py in the you get the value. If it's given, you filter by it:

    def dynamic_articles_view(request):
        context['object_list'] = article.objects.filter(title__icontains=request.GET.get('search'))
        return render(request, "encyclopedia/article_detail.html", context)