xaos_xv
xaos_xv

Reputation: 769

Django - Slugify string and use it only in url

I have get_aboslute_url function in my model in Django. Here is my code:

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

Here is my code for detail function:

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)

And here is my problem. I want to use author and title as a slug in my url. So url should look like this author-name/title-of-book. How can I do it?

Thanks in advance for the help.

Upvotes: 1

Views: 738

Answers (1)

Astik Anand
Astik Anand

Reputation: 13047

You can do this way:

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

Upvotes: 1

Related Questions