我正在尝试在查询时显示与给定对象相关的所有django-taggit标签。
我曾尝试像这样在我的search_result.html模板中添加此功能,但未显示任何标签:
{% 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 display them in the span below -->
<div class="text-center">
<span class="label label-info">{{ result.object.ptags.name }}</span>
</div>
</div>
{% endfor %}
</ol>
</div>
{% endif %}
我的模特:
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()
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
我的自定义form.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
我正在将表单传递给这样的视图:
class FacetedSearchView(BaseFacetedSearchView):
form_class = FacetedProductSearchForm
facet_fields = ['ptags']
template_name = 'search_result.html'
paginate_by = 6
context_object_name = 'object_list'
我该怎么做?
答案 0 :(得分:0)
您能试试看吗
<span class="label label-info">{{ result.object.ptags.names }}</span>
您可以遍历ptags.names
查询集以显示各个标签,如下所示:
{% for tag in result.object.ptags.names %}
{{ tag }}
{% endfor %}