使Django slug和id一起工作?

时间:2018-10-19 09:11:28

标签: django django-urls slug id slugify

我希望我的URL像Stackoverflow一样包含id和slug,但是slug可能无法正常工作,而不是像这样

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

URL就是这样

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

我的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})

我的views.py:

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

我的urls.py:

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

谢谢

1 个答案:

答案 0 :(得分:3)

调用slug()方法获取值。

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

或将其定义为该类的专有财产

@property
def slug(self):
    ...