GrantU
GrantU

Reputation: 6555

Django Slug Not Working In get_absolute_url

Whats wrong with this code? get_absolute_url is blank when rendered in my template, which means It's failing somewhere.

I suspect it's the slug as this is the first time I have tried to use it within Django:

Thanks

Model:

class Entry(models.Model):
    title = models.CharField(max_length=200)
    slug = models.SlugField(max_length=255, unique=True)

    def get_absolute_url(self):
       return reverse("EntryDetail", kwargs={"slug": self.slug})

URL:

 url(r'^entry/(?P<slug>[^\.]+).html',
                           blog_views.EntryDetail.as_view(),
                           name='blog_entry'),

View:

class EntryDetail(DetailView):

    context_object_name = 'entry'
    template_name = "blog.entry.html"
    slug_field = 'slug'

    def get_object(self):
        return get_object_or_404(Entry, url=self.slug_field)

Upvotes: 2

Views: 3362

Answers (1)

Glyn Jackson
Glyn Jackson

Reputation: 8354

Based on what @Peter DeGlopper stated in comments: It looks like your trying to get the absolute URL using a Class Based View. Don't use reverse here, instead you should always give your URLs a name, and then refer to that.

For example this is how it should look:

model

@models.permalink
def get_absolute_url(self):
   return 'blog_entry', (), {'slug': self.slug}

urls

url(r'^entry/(?P<slug>[^\.]+).html',
     blog_views.EntryDetail.as_view(),
       name='blog_entry'),

Upvotes: 3

Related Questions