【问题标题】:Django tag filtering issueDjango标签过滤问题
【发布时间】:2015-03-08 11:43:58
【问题描述】:

我的代码有问题,我想过滤标签,只显示具有特定标签的文章。

这是我的代码: 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)

这部分代码是我的问题

它给了我这个错误信息:StopIteration at /article/tags/2 没有提供异常信息


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

我该如何解决?


尝试过的解决方案:

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

/article/tags/2 处的类型错误 int() 参数必须是字符串或数字,而不是 '_TaggableManager'

【问题讨论】:

  • 我用的是 django-taggit 包

标签: python django tags django-filter django-taggit


【解决方案1】:

你应该找到具体的标签,然后通过它过滤文章:

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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-15
    • 2020-03-18
    • 1970-01-01
    • 2015-11-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-06
    相关资源
    最近更新 更多