Django - Slugify字符串并仅在url中使用它

时间:2018-02-24 12:48:34

标签: django

我在Django的模型中有get_aboslute_url函数。这是我的代码:

def get_absolute_url(self):
    return reverse('detail', args=[self.author.full_name, self.title])

以下是detail功能的代码:

def detail(request, author, title):
    book = get_object_or_404(Book,
                             author__full_name=author,
                             title=title)

    context = {'book': book}

    return render(request, 'booksreview/books_list.html', context)

这是我的问题。我想在我的网址中使用authortitle作为slug。所以网址应该如下author-name/title-of-book。我该怎么办?

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

你可以这样做:

class Book(models.Model):
    author = ......
    slug = models.SlugField(max_length=150)
    title = models.CharField(max_length=100)

    def save(self):
        if not self.id:
             self.slug = slugify(self.author__full_name + self.title)

    def get_absolute_url(self):
        return reverse('detail', kwargs={'slug': self.slug})