Django tag filtering issue

我的梦境 提交于 2019-12-25 04:51:57

问题


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:


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)


来源:https://stackoverflow.com/questions/28926015/django-tag-filtering-issue

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!