Django Шаблон DetailView не показывает детали - PullRequest
0 голосов
/ 22 февраля 2020

Я изучаю Django веб-фреймворк за последние несколько дней, и это довольно круто. Я изучаю представления на основе классов для отображения содержимого. Я создал простой пример моделей school(name,principal,location) и student(name,age,school(foreign key)). Модели:

from django.db import models

# Create your models here.

# Create a School model with different classes
# School Model with Name,Pricipal & Location
class School(models.Model):

    # Create name,pricipal,location fields for the School
    name = models.CharField(max_length=256)
    principal = models.CharField(max_length=256)
    location = models.CharField(max_length=256)

    # method to pritn the string representation of the class
    def __str__(self):
        return self.name

# Create a stduent model of the school
class Student(models.Model):

    # create name,age,school fields for students
    name = models.CharField(max_length=256)
    age = models.PositiveIntegerField()
    school = models.ForeignKey(School, related_name='stduents', 
                                            on_delete=models.CASCADE)

    # method to print the string representation of stduent class
    def __str__(self):
        return self.name

Мой urls.py равен

from django.urls import path
from . import views

# Create a app_name for template tagging
app_name = 'CBV_app'

urlpatterns = [
     path('',views.SchoolListView.as_view(),name='list'),
     path('<int:pk>/',views.SchoolDetailView.as_view(),name='detail')
]

Основной urls.py

from django.contrib import admin
from django.urls import path, include
from CBV_app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.IndexView.as_view()),
    path('CBV_app/',include('CBV_app.urls', namespace='CBV_app'))
]

Внешний ключ в модели студента имеет related_name = 'студентов' , который связан с моделью школы. Я зарегистрировал модели и создал представления на основе классов (списки и подробные представления) в файле views.py. Файл views.py

from django.shortcuts import render
from django.views.generic import View, TemplateView, ListView, DetailView
from django.http import HttpResponse
from . import models

# Create your views here.



# create a view using the built in template view
class IndexView(TemplateView):

   # template_name is the class object attribute of class TemplateView
   # Just pass in the html file that need to be displayed
   template_name = 'index.html'


# create a list view class for school inheriting from ListView
class SchoolListView(ListView):


    context_object_name = 'schools'


    # connect this to the created models
    # this provides the models each record in the form of list
    model = models.School


# create a detail view for the school by inheriting the DetailView
class SchoolDetailView(DetailView):

    context_object_name = 'school_detail'

    # set the view to the model
    model = models.School
    # point the class attribute template_name to point the detail view

    template_name = 'CBV_app/school_detail.html'

А мой файл student_detail.html

{% extends "CBV_app/CBV_app_base.html" %}

{% block body_block %}

<div class="jumbotron">
<p class="display-4">Welcome to school details page</p>
<p class="h3">School details:</p>
<p class="lead">School Id: {{school_detail.id}}</p>
<p class="lead">Name: {{school_detail.name}}</p>
<p class="lead">Principal: {{school_detail.principal}}</p>
<p class="lead">Location: {{school_detail.location}}</p>
<h3 class="h3">Student Details:</h3>
  <!-- students is the related name given in the model with the foreign key -->
  <!-- which connects with the school model -->
  {% for stu in student_detail.students.all %}
    <p>{{stu.name}} who is {{stu.age}} years old</p>
  {% endfor %}
</div>

{% endblock %}

Я создал две ссылки в моем school_list. html, который открывает соответствующую страницу сведений о школе. и отображает контент. После открытия страницы с подробностями я не могу просмотреть информацию о учениках соответствующей школы. Я проверял файлы много раз, но не смог выяснить, в чем причина. Я приложил изображение Нет. учеников школьной модели и Страница сведений о школе для справки.

Может кто-нибудь помочь мне, как это исправить? Заранее спасибо.

1 Ответ

0 голосов
/ 22 февраля 2020

Во-первых, в названии вашей модели Student есть опечатка: в названии вы указали "stduents", но в своем шаблоне вы используете "студентов".

Во-вторых , вы используете соответствующее имя в неправильной (или не существующей) модели в вашем шаблоне: Измените

{% for stu in student_detail.students.all %}

на

{% for stu in school_detail.students.all %}

в вашем шаблоне.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...