gpt4 book ai didi

python - Django NoReverseMatch : trying to get slug in a template

转载 作者:太空宇宙 更新时间:2023-11-03 17:30:11 25 4
gpt4 key购买 nike

我需要创建一个页面,其中包含具有特定标签的文章。

模型.py

class Tag(models.Model):
title = models.CharField('Title', unique=True, max_length=40, primary_key=True)
description = models.TextField('Description', max_length=300,
help_text='Short description for this tag')
tag_slug = models.SlugField()

def __str__(self):
return self.title

def get_absolute_url(self):
return reverse("tagged_posts", kwargs={"tag_slug": self.tag_slug})

def save(self, force_insert=False, force_update=False, using=None,
update_fields=None):
self.tag_slug = slugify(self.title)
super(Tag, self).save()

在关心帖子的类中,我有一个多对多的关系:

assoc_tags = models.ManyToManyField(Tag)

View .py

def tagged_posts(request):
tag = Tag.objects.select_related().get(tag_slug=tag_slug) #I thought it would work, but it didn't
posts = tag.post_set.all()
return render(request, 'blog/tagged_posts.html', {'posts': posts, 'tag': tag, })

在 admin.py 中,我写道 tag_slug 是预填充字段。

url.py:

url(r'^tag/(?P<tag_slug>\S+)$', views.tagged_posts, name='tagged_posts'),

模板:

Tagged under
{% for tag in object.assoc_tags.all %}
<a href="{% url 'tagged_posts' tag_slug=object.tag_slug %}">{{ tag }}</a>
{% if not forloop.last %}, {% endif %}
{% endfor %}

结果,我遇到了这个错误:

NoReverseMatch: Reverse for 'tagged_posts' with arguments '()' and keyword arguments '{'tag_slug': ''}' not found. 1 pattern(s) tried: ['blog/tag/(?P\S+)$']**

你能告诉我,我做错了什么吗?

最佳答案

这不是很清楚,因为我认为您没有发布正确的 View ,但看起来您在帖子中引用了 tag_slug,而不是在标签上。

<a href="{% url 'tagged_posts' tag_slug=tag.tag_slug %}">

关于python - Django NoReverseMatch : trying to get slug in a template,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31968493/

25 4 0