Django tag filtering issue

2019-08-29 07:17发布

I have a problem with my code, I want to filter the tags, to show only my articles who has the a certain tag.

here is my code: views.py

from article.models import Article

def innertag(request, id):
    context = {}
    populateContext(request, context)
    return render_to_response('innerajouter.html', context, Context({"articles" : Article.objects.filter(tags__name=Article.tags), "tag" : get_object_or_404(Article.tags, id=id)}))

"articles" : Article.objects.filter(tags__name=Article.tags)

This part of my code is the problem

it gives me this error message: StopIteration at /article/tags/2 No exception message supplied


innerajouter.html

<h3>For the tag: {{ tag.name }}</h3>

{% for article in articles %}
    <h1>{{ article.titre }}</h1>
    <h5>{{ article.auteur }}</h5>
    <p>{{ article.contenu }}</p>
{% endfor %}

from django.db import models
from taggit.managers import TaggableManager

class Article(models.Model):
    titre = models.CharField(max_length=100)
    auteur = models.CharField(max_length=42)
    contenu = models.TextField(null=True)
    tags = TaggableManager()

    def __str__(self):
        return self.titre

How Can I resolve that ?


Solution tried :

"articles" : Article.objects.filter(tags=Article.tags)

TypeError at /article/tags/2 int() argument must be a string or a number, not '_TaggableManager'

1条回答
做个烂人
2楼-- · 2019-08-29 07:43

You should find the concrete tag and then filter articles by it:

from django.shortcuts import get_object_or_404, render
from taggit.models import Tag

def innertag(request, id)
    tag = get_object_or_404(Tag, id=id)
    articles = Article.objects.filter(tags=tag)
    context = {'tag': tag, 'articles': articles}
    populateContext(request, context)
    return render(request, 'innerajouter.html', context)
查看更多
登录 后发表回答