如何在 Django 管理中使用 taggit 添加标签

How to add tags using taggit in Django admin

我正在尝试使用 django admin 将标签添加到我的博客应用程序,但每次我通过管理控制台添加标签时,我都会收到此错误 Can't call similar_objects with a non-instance manager

这是因为我没有在管理中保存标签还是因为我错误地实现了 taggit?

这是我定义视图和显示以及文章的地方,我尝试使用 taggit 抓取类似的文章

def article(request, slug):
    article = Post.objects.filter(slug=slug).values()
    article_info = {
        "articles": article,
        "related_articles" : Post.tags.similar_objects()
    }

    return render(request, 'article.htm', article_info)

更新

这就是我的 post 模型的样子

STATUS = (
    (0,"Draft"),
    (1,"Publish")
)

class Post(models.Model):
    title = models.CharField(max_length=200, unique=True)
    slug = models.SlugField(max_length=200, unique=True)
    author = models.CharField(max_length=200, unique=True)
    author_biography = models.TextField(default="N/A")
    updated_on = models.DateTimeField(auto_now= True)
    content = models.TextField()
    upload_image = models.ImageField(default="default.png", blank=True)
    created_on = models.DateTimeField(auto_now_add=True)
    status = models.IntegerField(choices=STATUS, default=0)
    tags = TaggableManager()

    class Meta:
        ordering = ['-created_on']

    def __str__(self):
        return self.title

通常,这种类型的结构是使用 ManyToMany 关系构建的。

按照这种方式,您的代码应如下所示:

class Tag(models.Model):
    name = models.CharField(max_length=255)

class Post(models.Model):
    title = models.CharField(max_length=200, unique=True)
    tag = models.ManyToManyField(Tag)

向 post 添加标签:

post_obj = Post.objects.get(title="le title")
tag = Tag.objects.get(name="le name")
post_obj.tag.add(tag)

查询:

post_obj = Post.objects.get(title="le title")
tags_in_post = post_obj.tag.all()

这应该有助于您的页面呈现。假设你想显示每个 post 并且在其中显示每个,你的代码应该是这样的:

// in the end of the view function:
return render(request, 'article.htm', context={'post': article_info})

// inside the template:

{% for p in post %}
<li> <span> {{p.title}} </span>

    {% for tag in post.tag %}
    <ul> {{tag.name}} </ul>
    {% endfor %}

</li>
{% endfor %}

好的,我看到问题了。

您正在尝试访问 class Post 上的标签,而不是 Post 的实例。但是,您还使用了 filter()values() 并且变量名称是单数,所以我认为那里也可能存在误解。

我假设你想做的是这个;

def article(request, slug):
    article = Post.objects.get(slug=slug)
    article_info = {
        "article": article,
        "related_articles" : article.tags.similar_objects()  # Instance of Post is article
    }

    return render(request, 'article.htm', article_info)