user2492270
user2492270

Reputation: 2285

Django DetailView failing to find object based on SLUG

models.py

class Tag(models.Model):
    name = models.CharField(max_length=64, unique=True)     
    slug = models.SlugField(max_length=255, unique=True)

    def save(self, *args, **kwargs):
        self.slug = slugify(self.name)
        super(Tag, self).save(*args, **kwargs)


urls.py

url(r'^tag/(?P<slug>[A-Za-z0-9_\-]+)/$',
    TagDetailView.as_view(),
    name='tag_detail'),      


views.py

class TagDetailView(DetailView):
    model = Tag
    template_name = 'tag_detail_page.html'
    context_object_name = 'tag'

This is giving me a 404:

Page not found (404)
http://localhost:9999/tag/RandomTag/
No tag found matching the query

Why does Django fail to fetch the correct object based on the slug field?

Upvotes: 3

Views: 1334

Answers (2)

meshy
meshy

Reputation: 9076

Timmy's answer is correct in ascertaining the problem -- slugs are lowercase. He suggests you use a lowercase url. Not a bad solution... but perhaps you like the url like that?

If you want the slug to be case insensitive, set slug_field = 'slug__iexact' on your view.

Upvotes: 1

Timmy O&#39;Mahony
Timmy O&#39;Mahony

Reputation: 53971

Django's slugify method:

Converts to lowercase, removes non-word characters (alphanumerics and underscores) and converts spaces to hyphens. Also strips leading and trailing whitespace.

you are looking for a Camel Case'd tag:

http://localhost:9999/tag/RandomTag/

you need to use lowercase:

http://localhost:9999/tag/randomtag/  # or `random-tag` depending on the name

Check your DB to see exactly how the slug is saved

Upvotes: 4

Related Questions