【问题标题】:Django search bar not getting to the right pageDjango搜索栏没有进入正确的页面
【发布时间】:2019-09-01 20:30:56
【问题描述】:

我的页面有两种搜索服务的方式——一种是搜索栏,另一种是可点击的类别。可点击类别转到一个页面,该页面具有附加到视图的类别主键,搜索栏结果没有附加类别 pk。因此,出于这个原因,我创建了两个单独的视图。问题是两个视图都转到 index.html 的同一页面。我希望搜索栏转到 index_search.html。我想我正确设置了所有内容,但它仍然无法正常工作。

两种视图:搜索视图、可点击项目视图:

#search form view
def service_finder(request):
    model = Service
    if ('s' in request.GET) and request.GET['s'].strip():
        query_string = request.GET['s']
        #get query is just searching for search terms in those fields of the query set
        entry_query = get_query(query_string,['description', 'tags', 'category'])
        table = Service.objects.filter(entry_query)[:60]
    return render(request, 'index_search.html', {'table': table})

 #clickable items view
 def servicesListView(request, category):
    model = Service
    table = Service.objects.filter(category=category)[:60]
    return render(request, 'index.html', {'table': table})

这是包含搜索栏和可点击项目的 html 模板:

    {% block content %}
<main class="category">

    {% include "search_form.html" %}

    <section class="category-list">
        <div class="container">
            <div class="row">
                {% for service in service_cat %}
                <div class="col-sm-12 col-lg-6">
                     <a
                         href="{% url 'services_list' service.category %}"
                        {{ service.category }}
                    </a>
                </div>
                {% endfor %}
            </div>
        </div>
    </section>
</main>
{% endblock %}

这里是搜索栏文件或search_form.html:

    <div class="search-bar">
    <div class="container">
        <form method="get" action="{% url 'service_finder' %}">
            {% csrf_token %}
            <div class="input-group">
                <input name='s' value="{{request.GET.s}}"  type="text" class="form-control" placeholder="Search services" aria-label="Search" aria-describedby="search">
                <div class="input-group-append">
                    <button class="btn btn-secondary" type="submit" id="button-addon2">Go</button>
                </div>
            </div>
        </form>
    </div>
</div>

这是两个页面的网址:

    path('services/<category>/', views.servicesListView, name='services_list'),
    path('services/find/', views.service_finder, name='service_finder'),

已解决:

通过切换 url 的顺序来解决这个问题。

【问题讨论】:

    标签: django search django-views django-urls


    【解决方案1】:

    这是因为路径 /services/find/ 匹配之前的模式 /services/&lt;category&gt;/。只是解释修复工作的原因!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-16
      • 1970-01-01
      • 2021-01-28
      相关资源
      最近更新 更多