Читал много инфы относительно slug в django, но нигде тема не раскрыта полностью. У меня есть модель жанр книг, соответственно нужно чтобы страница с каждым жанром в url использовала не id а slug. То есть с такого url - elib.live/book_genre/1 сделать например такой - elib.live/book_genre/nauka.
models.py
class BookGenre(models.Model):
name = models.CharField(max_length=86)
image = models.ImageField(default=None, upload_to='products_images/', blank=True, null=True)
slug = models.SlugField(max_length=255, unique=True, db_index=True, default=None, blank=True, null=True)
is_active = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __str__(self):
return self.name
class Meta:
verbose_name = "Book Genre"
verbose_name_plural = "Book Genres"
admin.py
class BookGenreAdmin(admin.ModelAdmin):
list_display = ['name','is_active']
prepopulated_fields = {"slug": ("name",)}
class Meta:
model = BookGenre
admin.site.register(BookGenre, BookGenreAdmin)
views.py
def home(request):
book_genrels = BookGenre.objects.filter(is_active=True).order_by('id')
return render(request, 'pages/index.html', locals())
def audiobook_genre(request, post_slug):
book_genrels = BookGenre.objects.filter(is_active=True).order_by('id')
book_genre = BookGenre.objects.filter(id=post_slug, is_active=True)
audiobook = AudioBook.objects.filter(genre=post_slug, is_active=True).order_by('created').reverse()
return render(request, 'pages/genre-page.html', locals())
urls.py
url(r'^audiobook_genre/<slug:post_slug>/', views.audiobook_genre, name='audiobook_genre'),
index.html
{% for genre in book_genrels %}
<a href="{% url 'audiobook_genre' genre.slug %}">
{% endfor %}