Django DetailView 不在模板中显示数据

Django DetailView don't show data in template

您好,我刚开始在 Django 中使用 CBV。我的 ListView 工作正常,它可以在除 DetailView 之外的模型中获取 id。它不显示详细数据。

https://drive.google.com/file/d/17yeU-LdvV_yLjnBB2A2gYt5ymSeKvPAR/view?usp=sharing

这里是代码:

models.py:

class School(models.Model):
    name = models.CharField(max_length=125)
    principal = models.CharField(max_length=125)
    location = models.CharField(max_length=125)

def __str__(self):
    return self.name

class Student(models.Model):
    name = models.CharField(max_length=70)
    age = models.PositiveIntegerField()
    school = models.ForeignKey(School,related_name='students',on_delete=models.CASCADE)

    def __str__(self):
        return self.name

urls.py:

  urlpatterns = [
    path('',views.School_List.as_view(),name='school_list'),
    path('<int:pk>/',views.School_Detail.as_view(),name='school_detail'),
]

views.py:

class School_List(ListView):
    context_object_name = 'schoollist'
    model = School

class School_Detail(DetailView):
    contex_object_name = 'schooldetail'
    model = School
    template_name = 'basicapp/School_detail.html'

detail.html:

{% block content %}
    <h1>Site showing School Detail</h1>
    <div class="container">
        <div class="p-5 text-white bg-dark rounded-3 container">
            <p>Name: {{schooldetail.name}}</p>
            <p>Principal: {{schooldetail.principal}}</p>
            <p>Location: {{schooldetail.location}}</p>
            <h2>Student: </h2>
            {% for student in schooldetail.students.all %}
                <p>{{student.name}} who is {{student.age}} years old</p>
            {% endfor %}
        </div>
    </div>
{% endblock %}

谢谢

School_Detail 中,您使用 Student 作为 Model 而不是 School Model.

将您的 ModelStudent 更改为 School

class School_Detail(DetailView):
    context_object_name = 'schooldetail'
    model = School                       #<---- change model name here
    template_name = 'basicapp/School_detail.html'

它应该是 {{schooldetail.school.name}} 而不是 {{schooldetaill.name}},因为您在详细信息视图中使用 Student 模型,因此您可以通过 Student 模型的外键字段访问 School 模型。

{% block content %}
        <h1>Site showing School Detail</h1>
        <div class="container">
            <div class="p-5 text-white bg-dark rounded-3 container">
                <p>Name: {{schooldetail.school.name}}</p>
                <p>Principal: {{schooldetail.school.principal}}</p>
                <p>Location: {{schooldetail.school.location}}</p>
                <h2>Student: </h2>
                {% for student in schooldetail.students.all %}
                    <p>{{student.name}} who is {{student.age}} years old</p>
                {% endfor %}
            </div>
        </div>
    {% endblock %}

打错了。代码不起作用,因为在:

class School_Detail(DetailView):
    contex_object_name = 'schooldetail' 
    model = School
    template_name = 'basicapp/School_detail.html'

我刚刚在 context_object_name 中遗漏了一个字母 't'。