### search app作成
$ python3 manage.py startapp search
setting.py
INSTALLED_APPS = [ 'shop', 'search', // 省略 ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'shop', 'templates/'), os.path.join(BASE_DIR, 'search', 'templates/')], // 省略 }, ]
search/urls.py
from django.urls import path from . import views app_name = 'search' urlpatterns = [ path('', views.search_result, name='search_result'), ]
urls.py
urlpatterns = [ path('admin/', admin.site.urls), path('shop/', include('shop.urls')), path('search/', include('search.urls')), ]
search/views.py
from django.shortcuts import render from shop.models import Product def search_result(request): products = Product.objects.all() return render(request, 'search.html', {'products': products})
navbar.html
<form class="form-inline my-2 my-lg-0" action="{% url 'search:search_result' %}" method="get"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="q"> <button class="btn btn-secondary my-2 my-sm-0" type="submit"><i class="fas fa-search"></i></button> </form>
search.html
{% extends "base.html" %} {% load static %} {% block metadescription %} We have a variety of stunning and comfy cushions. Lock for the one that suits your needs. {% endblock %} {% block title %} Search - Perfect Cushion Store {% endblock %} {% block content %} <div> <p class="text-center my_search_text">You have searched for: <b>"{{ query }}"</b></p> </div> <div class="container"> <div class="row mx-auto"> {% for product in products %} <div class="my_bottom_margin col-9 col-sm-12 com-md-4 com-md-12 col-lg-4"> <div class="card text-center" style="min-width: 18rem;"> <a href="{{product.get_url}}"><img class="card-img-top my_image" src="{{product.image.url}}" alt="{{product.name}}"></a> <div class="card-body"> <h4>{{product.name}}</h4> <p>${{product.price}}</p> </div> </div> </div> {% empty %} <div class="row mx-auto"> <p class="text-center my_search_text">0 results found.</p> </div> {% endfor %} </div> </div> {% endblock %}
OKでしょう。