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][1]
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
views.py:
class School_List(ListView):
context_object_name = 'schoollist'
model = School
class School_Detail(DetailView):
contex_object_name = 'schooldetail'
model = Student
template_name = 'basicapp/School_detail.html'
detail.html:
{% block content %}
<h1>Site showing School Detail</h1>
<div >
<div >
<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
CodePudding user response:
In School_Detail
you use Student
as Model
instead of School
Model
.
Change your Model
from Student
to School
as
class School_Detail(DetailView):
contex_object_name = 'schooldetail'
model = School #<---- change model name here
template_name = 'basicapp/School_detail.html'
CodePudding user response:
it should be {{schooldetail.school.name}}
not {{schooldetaill.name}}
as you using Student model in your details views so you can access School model via your foreign key fields of Student model.
{% block content %}
<h1>Site showing School Detail</h1>
<div >
<div >
<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 %}