【问题标题】:Django get content associated to the tag when clickedDjango在单击时获取与标签关联的内容
【发布时间】:2015-03-08 10:38:33
【问题描述】:

我想知道如何过滤标签。

我的意思是:如果点击这个标签,显示所有有这个标签的文章。 (django - 1.7.4 和 python 2.7.9)

views.py

def tag(request):
    context = {}
    populateContext(request, context)
    return render_to_response('ajouter.html', context, Context({'tout_tags': Article.tags.all()}))

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

ajouter.html

{% for tag in tout_tags %}

<a href="{% url "article.views.innertag" tag.id %}">{{ tag.name }}</a>

{% endfor %}

innerajouter.html

<h3>For the tag: {{ tag.name }}</h3>
//How can I filter ? To get only the selectioned tags ?

这是我的项目的视图:

【问题讨论】:

  • 你能展示你的模型吗?那真的很有帮助。
  • 另外,是标记另一个模型,还是我不熟悉的一些 django 包?
  • 他好像在用django-taggit
  • 您的代码还有一些问题,我看到不知道能否解决问题。一,您应该在您的视图中将 tagID 更改为 id 。您也没有导入任何标签模型。此外,通常将经理附加到模型的首选方式是objects = TaggableManager(),但这取决于您。最后,您将不得不检查您正在使用的 django-taggit 的文档,以了解如何从数据库中获取标签并通过您正在使用的管理器使用这些标签过滤其他内容。
  • 好的,谢谢您的宝贵时间

标签: python django filter tags


【解决方案1】:

如果你想显示某个标签下的所有文章...

from django.template import RequestContext

def displayAllArticlesUnderTage(request, tagID):
    context = RequestContext(request)
    tag = tag.objects.get(id = tagID)
    #Note, I am not sure of your database relationship between the tags and 
    #the articles so you will probably have to change the next line...
    articles = Article.objects.filter(tag = tag)
    context_dict = { "articles" : articles, "tag" : tag }
    return render_to_response([your template name], context_dict, context)

我推测您的文章与您的标签对象的关系。如果这是错误的,请告诉我。


我的答案将取决于您的文章的显示方式。我将在这里给出一般语法...

{% for article in articles %}

    <h1>{{ article.titre }}</h1>
    <h5>{{ article.autuer }}</h5>
    <p>{{ article.contre }}</p>
    *Whatever other things you need from each article*
{% endfor &}

【讨论】:

  • NameError at /article/tags/2 global name 'tags' is not defined 我该如何解决这个问题? (我更改了代码以适应它)
  • def innertag(request, tagID): context = {} 文章 = Article.objects.filter(tag = tags) populateContext(request, context) return render_to_response('innerajouter.html', context, Context ({"articles" : 文章, "tag": get_object_or_404(Article.tags, id=tagID)}))
  • 你必须插入你的标签模型才能工作。
  • 如果我使用 id=id 而不是 id=tagID 会有区别吗?
  • 不,我在函数中放入的 tagID 只是一个参数。我可以是任何名字。只要您的视图中的参数名为 id,id=id 的工作方式相同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-09
  • 2013-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-29
相关资源
最近更新 更多