Я создал панель поиска, которая осуществляет поиск по названию продукта. Теперь я хотел бы изменить это на поиск по категориям, но мне сложно. Вот мой файл URL: '' '
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.marketplaceHome, name='marketplace-home'),
url(r'^search/$', views.search, name='search'),
url(r'^contact/$', views.Contact, name='contact'),
url(r'^(?P<category_slug>[-\w]+)/(?P<product_slug>[-\w]+)/$', views.productPage, name='product_detail'),
url(r'^(?P<category_slug>[-\w]+)/$', views.marketplaceHome, name='products_by_category'),
url('^cart$', views.cart_detail, name='cart_detail'),
url(r'^cart/add/(?P<product_id>[-\w]+)/$', views.add_cart, name='add_cart'),
url(r'^cart/remove/(?P<product_id>[-\w]+)/$', views.cart_remove, name='cart_remove'),
url(r'^cart/remove_product/(?P<product_id>[-\w]+)/$', views.cart_remove_product, name='cart_remove_product'),
]
' '' views.py '' '
from __future__ import unicode_literals
from django.shortcuts import render, get_object_or_404, redirect
from .models import Category, Product, Cart, CartItem
from django.core.exceptions import ObjectDoesNotExist
from . import forms
# Create your views here.
def marketplaceHome(request, category_slug=None):
category_page = None
products = None
if category_slug !=None:
category_page = get_object_or_404(Category, slug=category_slug)
products = Product.objects.filter(category=category_page, available=True)
else:
products = Product.objects.all().filter(available=True)
return render(request, 'marketplacehome.html', {'category': category_page, 'products': products})
def productPage(request, category_slug, product_slug):
try:
product = Product.objects.get(category__slug=category_slug, slug=product_slug)
except Exception as e:
raise e
return render(request, 'product.html', {'product': product})
def search(request):
products = Product.objects.filter(name__contains=request.GET['name'])
return render(request, 'marketplacehome.html', { 'products': products})
' 'template. html' ''
<ul class="navbar-nav ml-auto">
<form class="form-inline" action="{% url 'search' %}", method="GET">
<div class="input-group">
<input type="text" name="name" class="form-control" placeholder="Location" aria-label="Search" name="query">
<div class="input-group-append">
<button type="button" class="btn btn-warning" name="button"><i class="fas fa-search"></i></button>
</div>
</div>
'' 'models.py' ''
class Category(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
class Meta:
ordering = ('name',)
verbose_name = 'category'
verbose_name_plural = 'categories'
def get_url(self):
return reverse('products_by_category', args=[self.slug])
def __str__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=250, unique=True)
slug = models.SlugField(max_length=250, unique=True)
description = models.TextField(blank=True)
image = models.ImageField(upload_to="product", blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
single_price = models.DecimalField(max_digits=10, decimal_places=2)
twelve_lesson_price = models.DecimalField(max_digits=10, decimal_places=2)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
available = models.BooleanField(default=True)
class Meta:
ordering = ('name',)
verbose_name = 'product'
verbose_name_plural = 'products'
def get_url(self):
return reverse('product_detail', args=[self.category.slug, self.slug])
def __str__ (self):
return self.name
'' '
Эта структура успешно вернула продукты, которые были найдены по имени, но когда я изменил его на категории это не сработало. Любая помощь будет принята с благодарностью.