Home > Enterprise >  Django Model Linking
Django Model Linking

Time:08-14

How it should be:

  1. I choose a Book.
  2. A http://127.0.0.1:8000/<slug:book_slug> opens with a selection of pages that are associated with the book that I have chosen.

As it turns out:

  1. I choose a book.
  2. A http://127.0.0.1:8000/<slug:book_slug> opens with a choice of absolutely all created pages.

My Code:

models.py:

from django.db import models
from django.urls import reverse


class Book(models.Model):

    title = models.CharField(max_length=(500))

    slug = models.SlugField(
                            max_length=(150),
                            unique=True,
                            db_index=True,
                            verbose_name="URL"
                            )

    def __str__(self):
        return self.title

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


class Page(models.Model):

    title_title = models.ForeignKey('Book', on_delete=models.PROTECT)

    number_page = models.CharField(max_length=(500))

    def __str__(self):
        return self.number_page

urls.py:

from django.urls import path
from .views import First_page, Second_page

urlpatterns = [
    path('', First_page),
    path('<slug:book_slug>', Second_page, name='Second_page')
]

views.py:

from django.template.response import TemplateResponse
from .models import Book, Page
from django.shortcuts import get_object_or_404


def First_page(request):
    book = Book.objects.all()
    return TemplateResponse(request,  "first.html", {'book': book})


def Second_page(request, book_slug):
    page = Page.objects.all()
    get_object_or_404(Book, slug=book_slug),
    return TemplateResponse(request,  "second.html", {'page': page})

first.html:

{% extends 'index.html' %}
{% block content %}
{% for b in book %}
<ul>
  <li><a href="{{b.slug}}">{{b.title}}</a></li>
</ul>
{% endfor %}
{% endblock %}

second.html:

{% extends 'index.html' %}
{% block content %}
{% for p in page %}
<ul>
  <li><p>{{p.number_page}}</p></li>
</ul>
{% endfor %}
{% endblock %}

CodePudding user response:

In the following line, you're getting all pages:

page = Page.objects.all()

You need to filter based on the book_slug parameter:

page = Page.objects.filter(title_title__slug=book_slug)
  • Related