messier101
messier101

Reputation: 101

Django NoReverseMatch: trying to get slug in a template

I need to create a page where there will be articles that have a certain tag.

models.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()

In class that cares for posts, I have a many-to-many relationship:

assoc_tags = models.ManyToManyField(Tag)

views.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, })

In admin.py I wrote that tag_slug is the prepopulated field.

urls.py:

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

template:

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 %}

As a result, I have this error:

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

Can you tell me, what am I doing wrong?

Upvotes: 1

Views: 273

Answers (2)

messier101
messier101

Reputation: 101

This tutoral - http://arunrocks.com/recreating-the-building-a-blog-in-django-screencast/ helped me to solve my problem. The link below - https://github.com/arocks/qblog/compare/tagview shows added tags functionality. As Daniel Roseman answered, I had incorrect reference in my template: instead of tag, I reffered to an "object".

Upvotes: 0

Daniel Roseman
Daniel Roseman

Reputation: 599628

It's not very clear, because I don't think you've posted the correct view, but it looks like you've referred to tag_slug on the post, rather than on the tag.

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

Upvotes: 1

Related Questions