djangodjango-urlsslugslugify

How can I make Django slug and id work together?


I want my URL to contain both id and slug like StackOverflow, but the slug is not working properly. Instead of being like this:

www.example.com/games/155/far-cry-5

the URL is like this:

www.example.com/games/155/<bound%20method%20Game.slug%20of%20<Game:%20Far%20Cry%205>>

My models.py :

class Game(models.Model):
    name = models.CharField(max_length=140)

    def slug(self):
        return slugify(self.name)

    def get_absolute_url(self):
        return reverse('core:gamedetail', kwargs={'pk': self.id, 'slug': self.slug})

My views.py :

class GameDetail(DetailView):
    model = Game
    template_name = 'core/game_detail.html'
    context_object_name = 'game_detail'

My urls.py :

path('<int:pk>/<slug>', views.GameDetail.as_view(), name='gamedetail')

Solution

  • Call the slug() method to get the value.

    return reverse('core:gamedetail', kwargs={'pk': self.id, 'slug': self.slug()})
    

    Or define it as a propery of the class

    @property
    def slug(self):
        ...