Фильтрация элементов по их точному названию - PullRequest
0 голосов
/ 20 февраля 2020

Я пытаюсь отфильтровать свои товары по точному названию, нажав на ссылку с заголовком. Мне удалось отобразить заголовки, но когда я нажимаю на одну из них, я получаю сообщение об ошибке: Reverse for 'category_search' with arguments '('',)' not found. 1 pattern(s) tried: ['search/(?P<category_id>[0-9]+)$'], которое указывает на функцию TitleView.

views.py - Просто чтобы очистить некоторые вещи используется для фильтрации элементов по их категории, которая находится на другой странице, но результаты отображаются при поиске. html

def category_view(request, category_id):
  item_list = Item.objects.filter(category__pk=category_id)
  category = Category.objects.get(pk=category_id)

  return render(request, "search.html", {'item_list': item_list, 'category': category})

def TitleView(request, title):
  item_list = Item.objects.filter(title__iexact=title)
  return render(request, "search.html", {'item_list': item_list})

def SearchView(request, category_id=None, title=None):
  if category_id:
      category = Category.objects.get(pk=category_id)
      item_list = Item.objects.filter(category__id=category_id)
  else:
      item_list = Item.objects.all()

  query = request.GET.get('q')
  if query:
      item_list = item_list.filter(title__icontains=query)

  price_from = request.GET.get('price_from')
  price_to = request.GET.get('price_to')

  item_list = item_list.annotate(
      current_price=Coalesce('discount_price', 'price'))

  if price_from:
      item_list = item_list.filter(current_price__gte=price_from)

  if price_to:
      item_list = item_list.filter(current_price__lte=price_to)

  context = {
      'item_list': item_list,
      'category': category,
  }
  return render(request, "search.html", context)

html шаблон:

    <div class="offset-md-1 col-md-2">
    <h2>Content Filter</h2> <br>
    <form method="GET" action="{% url 'core:category_search' category.id %}">
        <h5>Search</h5>
        <div class="form-row">
            <div class="form-group col-8">
                <div class="input-group">
                    <input class="form-control py-2 border-right-0 border" type="search" name="q"
                        placeholder="Brand..">
                    <span class="input-group-append">
                        <div class="input-group-text bg-transparent">
                            <i class="fa fa-search"></i>
                        </div>
                    </span>
                </div>
            </div>
        </div>
        <h5>Price from</h5>
        <div class="form-row">
            <div class="form-group col-5">
                <div class="input-group">
                    <input class="form-control py-2 border-right-0 border" type="search" name="price_from"
                        placeholder="Price from" value="{{request.GET.price_from}}">
                    <span class="input-group-append">
                        <div class="input-group-text bg-transparent">
                            <i class="fa fa-search"></i>
                        </div>
                    </span>
                </div>
            </div>
        </div>
        <h5>Price to</h5>
        <div class="form-row">
            <div class="form-group col-5">
                <div class="input-group">
                    <input class="form-control py-2 border-right-0 border" type="search" name="price_to"
                        placeholder="Price to" value="{{request.GET.price_to}}">
                    <span class="input-group-append">
                        <div class="input-group-text bg-transparent">
                            <i class="fa fa-search"></i>
                        </div>
                    </span>
                </div>
            </div>
        </div>
        <div class="form-row">
            <button type="submit" class="btn btn-outline-primary btn-md">Search</button>
        </div>
    </form>
</div>
<ul>
    {% for item in item_list %}
    <li>
        <a href="{% url 'core:title_search' title=item.title  %}">
            {{ item.title }}
        </a>
    </li>
    {% endfor %}
</ul>

URL:

  path('search/', SearchView, name='search'),
  path('search/<int:category_id>', SearchView, name='category_search'),
  path('search/<title>', TitleView, name='title_search'),
  path('bike-category/<category_id>', category_view, name='category'),

1 Ответ

1 голос
/ 20 февраля 2020

Вам необходимо указать категорию в контексте шаблона или использовать другой шаблон. Учитывая, что вы возвращаете список, я не совсем уверен, как вы собираетесь вытащить из него категорию.

Если вы предполагали, что это будет прямая ссылка на каждый из элементов, я рекомендуем не использовать title в качестве поискового объекта. Вместо этого добавьте SlugField в вашу модель и отметьте его как уникальный. Затем используйте это в своем URL:

path('search/<slug:slug>/', item_view, name='item_view'),

Тогда ваш вид будет:

def item_view(request, slug):
  item = Item.objects.select_related('category').get(slug__iexact=slug)
  return render(request, "search.html", {
    'item_list': [item],
    'category': item.category
  })

Редактировать:

def SearchView(request, category_id=None):
    if category_id:
      category = Category.objects.get(pk=category_id)
      item_list = Item.objects.filter(category__id=category_id)
  else:
      item_list = Item.objects.all()
  title = request.GET.get('title')
  if title:
      item_list = item_list.filter(title__iexact=title)
  else:
     query = request.GET.get('q')
      if query:
          item_list = item_list.filter(title__icontains=query)

      price_from = request.GET.get('price_from')
      price_to = request.GET.get('price_to')

      item_list = item_list.annotate(
          current_price=Coalesce('discount_price', 'price'))

      if price_from:
          item_list = item_list.filter(current_price__gte=price_from)

      if price_to:
          item_list = item_list.filter(current_price__lte=price_to)

  context = {
      'item_list': item_list,
      'category': category,
  }
  return render(request, "search.html", context)

URL:

 path('search/', SearchView, name='search'),
  path('search/<int:category_id>', SearchView, name='category_search'),
  path('bike-category/<int:category_id>', category_view, name='category'),

Шаблон:

    <div class="offset-md-1 col-md-2">
    <h2>Content Filter</h2> <br>
    <form method="GET" action="{% if category %}{% url 'core:category_search' category.id %}{% else %}{% url 'core:search' %}{% endif %}">
        <h5>Search</h5>
        <div class="form-row">
            <div class="form-group col-8">
                <div class="input-group">
                    <input class="form-control py-2 border-right-0 border" type="search" name="q"
                        placeholder="Brand..">
                    <span class="input-group-append">
                        <div class="input-group-text bg-transparent">
                            <i class="fa fa-search"></i>
                        </div>
                    </span>
                </div>
            </div>
        </div>
        <h5>Price from</h5>
        <div class="form-row">
            <div class="form-group col-5">
                <div class="input-group">
                    <input class="form-control py-2 border-right-0 border" type="search" name="price_from"
                        placeholder="Price from" value="{{request.GET.price_from}}">
                    <span class="input-group-append">
                        <div class="input-group-text bg-transparent">
                            <i class="fa fa-search"></i>
                        </div>
                    </span>
                </div>
            </div>
        </div>
        <h5>Price to</h5>
        <div class="form-row">
            <div class="form-group col-5">
                <div class="input-group">
                    <input class="form-control py-2 border-right-0 border" type="search" name="price_to"
                        placeholder="Price to" value="{{request.GET.price_to}}">
                    <span class="input-group-append">
                        <div class="input-group-text bg-transparent">
                            <i class="fa fa-search"></i>
                        </div>
                    </span>
                </div>
            </div>
        </div>
        <div class="form-row">
            <button type="submit" class="btn btn-outline-primary btn-md">Search</button>
        </div>
    </form>
</div>
<ul>
    {% for item in item_list %}
    <li>
        <a href="{% if category %}{% url 'core:category_search' category.id %}{% else %}{% url 'core:search' %}{% endif %}?title={{item.title}}">
            {{ item.title }}
        </a>
    </li>
    {% endfor %}
</ul>

Мне кажется, я правильно обработал атрибут действия формы и атрибуты ссылки href. Возможно, вам придется очистить их для вашей ситуации.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...