Search code examples
djangodetailview

Django DetailView don't show data in template


Hello I'm just starting use the CBV in Django. My ListView working normal it can get the id in models except DetailView. It don't show the detail data.

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

Here the code:

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 %}

Thank you


Solution

  • In School_Detail you use Student as Model instead of School Model.

    Change your Model from Student to School as

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