Answer the question
In order to leave comments, you need to log in
How do I make django understand that I need a specific slug for a specific entry in the database?
I have Book and Chapter models. Each book has many pages. If I make after the slug of the Chapter model unique, then in the case when I want the slug of the first page of the book1 to be 1, then an error is generated that such a slug already exists ...
That is, I will never achieve this:
/book1/1/
/book2/1/
class Book(models.Model):
some code
class Chapter(models.Model):
book= models.ForeignKey(Book, verbose_name="title", on_delete=models.CASCADE)
number = models.PositiveIntegerField(verbose_name="num chapter")
slug = models.SlugField(verbose_name="slug_to", null=True, blank=True)
def save(self, *args, **kwargs):
self.slug = self.number
super().save(*args, **kwargs)
class Base(View):
def get(self, request, *args, **kwargs):
book = Book.objects.all()
return render(request, "base.html", context={"book": book})
class BookDetail(DetailView):
model = Book
context_object_name = "book"
template_name = "book_detail.html"
slug_url_kwarg = "slug"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["chapter"] = Chapter.objects.filter(title=self.object)
return context
class ChapterRead(DetailView):
model = Chapter
context_object_name = "chapter"
template_name = "chapter_read.html"
slug_url_kwarg = "int"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["imgs"] = ImgChapter.objects.filter(chapter=self.object)
return context
from django.contrib import admin
from django.urls import path
from .views import *
urlpatterns = [
path("", Base.as_view(),name="book_list"),
path("<str:slug>/", BookDetail.as_view(), name="book_detail"),
path("<str:slug>/<str:int>/", ChapterRead.as_view(), name="chapter_detail")
]
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>tf</title>
</head>
<body>
{% for i in book%}
<a href="{{ i.slug }}"> {{i.name}}</a>
{% endfor %}
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ book.name }}
{% for i in chapter %}
<a href="{{ i.slug }}">{{ i.number }}</a>
{% endfor %}
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{{ chapter.number }}
{% for i in imgs %}
<img src="{{ i.img.url }}">
{% endfor %}
</body>
</html>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question