简体   繁体   中英

Displaying all Django-taggit tags for each given object

I'm trying to display all the django-taggit tags related to the given object when I'm querying.

I've tried adding this function within my search_result.html template like this but no tags are being displayed:

{% 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 %}

My Models:

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

My custom forms.py function:

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

And I'm passing the forms into the views like this:

class FacetedSearchView(BaseFacetedSearchView):

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

How can I do this?

Can you try this instead

<span class="label label-info">{{ result.object.ptags.names }}</span>

You can loop over the ptags.names queryset to display individual tags, like this:

{% for tag in result.object.ptags.names %}
    {{ tag }}
{% endfor %}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM