Django标签过滤问题 [英] Django tag filtering issue

查看:118
本文介绍了Django标签过滤问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

我这部分代码就是问题

它给我以下错误消息:位于/article/tags/2的StopIteration没有提供异常消息

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

我该如何解决?

尝试的解决方法:

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

在/article/tags/2处的

TypeError int()参数必须是字符串或数字,而不是'_TaggableManager'

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

推荐答案

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

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)

这篇关于Django标签过滤问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆