如何使用模板标签调用django-taggit标签

How to call django-taggit tags using templates tags

我想使用 Django Haystack 和 Elasticsearch 按多个 Django-taggit 标签进行过滤,我已经在自定义表单中编写了一个 facets 函数,但我无法检索与我的所选过滤器匹配的结果模板。

那我怎么可能这样做呢?

我的models.py:

class Product(models.Model):
    title = models.CharField(max_length=255, default='')
    slug = models.SlugField(null=True, blank=True, unique=True, max_length=255, default='')
    description = models.TextField(default='')

    ptags = TaggableManager()

    image = models.ImageField(default='')
    timestamp = models.DateTimeField(auto_now=True)

    def _ptags(self):
        return [t.name for t in self.ptags.all()]

    def get_absolute_url(self):
        return reverse('product',
                       kwargs={'slug': self.slug})


    def __str__(self):
        return self.title

我的习惯forms.py:

from haystack.forms import FacetedSearchForm

class FacetedProductSearchForm(FacetedSearchForm):

    def __init__(self, *args, **kwargs):
        data = dict(kwargs.get("data", []))
        self.ptag = data.get('ptags', [])
        super(FacetedProductSearchForm, self).__init__(*args, **kwargs)

    def search(self):
        sqs = super(FacetedProductSearchForm, self).search()

        if self.ptag:
            query = None
            for ptags in self.ptag:
                if query:
                    query += u' OR '
                else:
                    query = u''
                query += u'"%s"' % sqs.query.clean(ptags)
            sqs = sqs.narrow(u'ptags_exact:%s' % query)

        return sqs

在 Views.py 中传递表单:

class FacetedSearchView(BaseFacetedSearchView):

    form_class = FacetedProductSearchForm
    facet_fields = ['ptags']
    template_name = 'search_result.html'
    paginate_by = 6
    context_object_name = 'object_list'

如果需要,网址:

urlpatterns = [
    url(r'^$', HomeView.as_view()),
    url(r'^admin/', admin.site.urls),
    url(r'^product/(?P<slug>[\w-]+)/$', ProductView.as_view(), name='product'),
    url(r'^search/', FacetedSearchView.as_view(), name='haystack_search'),

] + static(MEDIA_URL, document_root=MEDIA_ROOT)

最后,在模板方面我有一个 search_form.html:

{% load staticfiles %}
<div class="col-md-6">
    <form class="search-form-container" action="/search/" method="get">
        <div class="form-group">
            <div class="icon-addon addon-lg">
                <input type="text" placeholder="Search for good..." class="form-control" name="q" id="q" autocomplete="off">
                <div id="selction-ajax"></div>
            </div>
        </div>



        <div class="col-md-3">
                <dl>

           <!-- Checkbox is placed below -->

                <div>
                  <input class="facet" id="" type="checkbox" name="ptags" value="Solo" data-toggle="toggle" /> Solo
                </div>

                <div>
                  <input class="btn btn-info btn-sm pull-right" type="submit" value="apply filter" onclick="return onFacetChangeApplied();" />
                </div>

            </div>
    </form>
</div> 

谢谢。

在您的 search_indexes、运行 命令中为 ptags 添加 faceted=True 之后

  1. python manage.py clear_index

  2. python manage.py update_index

编辑您的 forms.py

         if self.ptag:
            query = None
            for ptags in self.ptag:
                if query:
                    query += u' OR '
                else:
                    query = u''
                    query += u'"%s"' % sqs.query.clean(ptags)
                    sqs = sqs.narrow(u'ptags_exact:%s' % query)

尝试这个并尝试调试您的 forms.py。

感谢@pankaj-sharma 它由 运行 python manage.py rebuild_index 完成!我现在可以按标签过滤,但问题是我无法在搜索结果中这样调用我的标签:

 {% if  page_obj.object_list %}

  <ol class="row top20">

  {% for result in page_obj.object_list %}

   <div class="showcase col-sm-6 col-md-4">

           <a href="{{ result.object.get_absolute_url }}">
              <h3>{{result.object.title}}</h3>
              <img src="{{ result.object.image }}" class="img-responsive">
           </a>

<!-- I want to call it in the span below -->

          <div class="text-center">
          <span class="label label-info">{{result.object.ptags.name}}</span>
          </div>

    </div>
  {% endfor %}
 </ol>
</div>