【问题标题】:Creating Django Filter in a bootstrap dropdown based on the django-admin created categories根据 django-admin 创建的类别在引导下拉列表中创建 Django 过滤器
【发布时间】:2017-11-06 06:17:32
【问题描述】:

我已经使用 Python-Django 2 个月了,但我没有足够的经验来继续我想做的事情。

我喜欢创建一个过滤器或下拉过滤器,这样任何人都可以从下拉列表中的for循环呈现的类别中进行选择,以按类别进行过滤或搜索。我设法使用 Whoosh 使用 Haystack 创建了完整搜索(您可以测试我的 Haystack Search here 并使用名为 ma​​rketing 的类别进行搜索)

有人可以详细说明如何根据下拉列表中循环的类别过滤我的列表吗?我真的很困惑。

这里是我工作中的 Haystack 搜索的代码

search_indexes.py

import datetime
from haystack import indexes
from haystack.query import EmptySearchQuerySet
from .models import Mentor
from .models import *


class MentorIndex(indexes.SearchIndex, indexes.Indexable):
    text = indexes.CharField(document=True, use_template=True)
    author1 = indexes.EdgeNgramField(model_attr='first_name')
    author2 = indexes.EdgeNgramField(model_attr='last_name')
    author3 = indexes.EdgeNgramField(model_attr='category')
    author4 = indexes.EdgeNgramField(model_attr='email')
    author5 = indexes.EdgeNgramField(model_attr='location')

    def get_model(self):
        return Mentor

    def index_queryset(self, using=None):
        """Used when the entire index for model is updated."""
        return self.get_model().objects.all()

home.html

<form method="get" action="/search/" class="navbar-form">
    <div class="form-group" style="display:inline;">
        <div class="input-group" style="display:table;">
            <input class="form-control" name="q" placeholder="Search Mentors Here. You can search by Location, Email, Name, e.t.c." autocomplete="off" autofocus="autofocus" type="text">
            <span class="input-group-btn" style="width:1%;">
                <button class="btn btn-danger" type="submit">
                    <span class=" glyphicon glyphicon-search"></span>
                </button>
            </span>
      </div>
    </div>
</form>

应用网址配置 (url.py)

from django.conf.urls import include, url
from mentoring_application.views import profile


urlpatterns = [
    url(r'^profile/(?P<pk>\d+)/$', profile, {}, name='mentor-profile'),
]

项目网址配置 (url.py)

from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from django.contrib import admin
from mentoring_application.views import HomeView, profile


admin.autodiscover()

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^$', HomeView.as_view()),
    url(r'^mentor/', include('mentoring_application.urls', namespace='mentor')),
    url(r'^search/', include('haystack.urls'))
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.views import View
from .models import *
from .models import Mentor
from django.shortcuts import render, get_object_or_404


# Create your views here.


class HomeView(View):
    # @staticmethod
    def get(self, request, *args, **kwargs):
        mentors = Mentor.objects.all()
        return render(request, "mentoring_application/home.html", {"mentors": mentors})


def profile(request, pk, template='mentoring_application/profile.html'):
    mentor = get_object_or_404(Mentor, pk=pk)  # pk is primary key, so url will be site.com/profile/3
    context = {'mentor': mentor}
    return render(request, template, context)

为了更清楚,这张图片显示了我喜欢做的类别过滤器。

【问题讨论】:

  • 发送模板数据的视图方法是什么?可以发一下吗?
  • @TimS。不确定我是否理解您的问题,但我已按要求进行了更新。但是,我想按类别创建一个过滤器。
  • 通常它的工作方式是您的视图根据您的过滤条件构建对象,然后将过滤后的对象/查询集发送到模板以呈现为下拉列表。我之前没有专门这样做过,但是视图的作用是将数据发送到模板进行渲染。
  • @TimS。如果可以的话,最好给我写一个解决方案。
  • 我目前无法编写完整的解决方案,但一个起点是根据过滤条件构建一个 httprequest,然后您可以将 mentor = get_object_or_404(Mentor, pk=pk) 替换为类似的内容mentor = Class.objects.filter(fieldname=criteria) 然后将其发送到您的视图,该视图可用于填充您的下拉列表。

标签: django python-2.7 django-views


【解决方案1】:

根据@TimS 的评论和其他社区的其他帮助,我编写了一个按类别过滤的解决方案,它可以工作。

以下是成功的秘诀:

home.html

这是类别表中的循环下拉列表。我创建了一个名为 category-filter 的名称元素,用于选择模板上的类别。

<div class="row" style="margin-bottom: 50px;">
    <div class="col-sm-6 pull-right">
        <form method="get">
            <select id="men-filter-cat" class="form-control" name="category-filter" onchange="this.form.submit();">
                <option value="all">Filter by category</option>
                {% for c in categories %}
                    <option value="{{ c.category }}" {% if selected == c.category %}selected=selected"{% endif %}>
                        {{ c.category }}
                    </option>
                {% endfor %}
            </select>
        </form>
    </div>
</div>

views.py

我重新定义了我的 HomeView 以使用名为 chosen_filter 的变量响应所选请求,而我的 views.py 变为:

class HomeView(View):
    def get(self, request, *args, **kwargs):
        mentors = Mentor.objects.all()
        chosen_filter = self.request.GET.get('category-filter')
        if chosen_filter:
            mentors = mentors.filter(category__category=chosen_filter)
        return render(request, "mentoring_application/home.html", {"mentors": mentors, 'selected': chosen_filter, 'categories': Category.objects.all().order_by('category')})


def profile(request, pk, template='mentoring_application/profile.html'):
    mentor = get_object_or_404(Mentor, pk=pk)  # pk is primary key, so url will be site.com/profile/3
    context = {'mentor': mentor}
    return render(request, template, context)

这对我有用。谢谢。

【讨论】:

  • 如果您最终没有使用下拉菜单,那么您可以使用 html 中的列表项来呈现您的类别并定义您的 html 以提交 onClick。
猜你喜欢
  • 2013-01-12
  • 2013-11-04
  • 2014-07-03
  • 2012-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-28
  • 2014-07-22
相关资源
最近更新 更多