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

标签 python django

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

模型.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/

相关文章:

python - 使用带有 pdist 和 squareform 的 nparray 创建距离矩阵

python - "SSL certificate verify failed"使用pip安装包

python - 子集 Pandas 中的多层次数据

python - 源文件 (.py) 未编译(.pyc 未更新)

python - Django 数据库查询往返

python - 在 Django 管理中添加和更改 View 的不同表单字段

python - Python 'and' 可以返回 None 吗?

Python 除以零错误

python - 是否可以在 django 中创建表单,让您直接在数据库中更改或添加?

python - Django 表单发布未获取 request.GET 中的值