Z
Z
Zenoviy Burychko2021-06-19 13:57:04
Django
Zenoviy Burychko, 2021-06-19 13:57:04

Why is the Django Slug not working?

I read a lot of information about slug in django, but nowhere is the topic fully disclosed. I have a book genre model, so the page with each genre in the url should use not an id but a slug. That is, from such a url - elib.live/book_genre/1, for example, do this - 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 %}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Misha Tarasov, 2021-06-19
@ZenoviyB

book_genre = BookGenre.objects.filter(id=post_slug, is_active=True).

id =post_slug . Replace id with slug

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question