Reputation: 147
I can't get the cat name and kitten type from the Cat and Kitten models into the template.
This is my model.py
class Cat(models.Model):
cat_name = models.CharField(max_length=200)
def __str__(self):
return self.cat_name
class Kitten(models.Model):
cat = models.ForeignKey(Cat, on_delete=models.CASCADE, related_name='kittens')
kitten_type = models.CharField(max_length=200)
def __str__(self):
return self.kitten_type
My views.py
class CatViews(generic.ListView):
model = Cat
template_name = 'polls/cats.html'
class CatDetail(generic.DetailView):
model = Kitten
template_name = 'polls/kitten.html'
My urls.py
urlpatterns = [
path('cats/', views.CatViews.as_view(), name='catlist'),
path('cats/<int:pk>/', views.CatDetail.as_view(), name='catdetail'),
]
And finally, polls/kitten.html
<h3>{{cat.cat_name}}</h3>
{% for kitty in cat.kittens.all %}
<p>{{ kitty.kitten_type }}</p>
{% endfor %}
The url is working, I'm just not able to display the fields from the models into their respective html elements. What am I missing?
Upvotes: 0
Views: 69
Reputation: 147
Figured it out. I had to set the CatDetailView to the Cat model, not Kitten model.
The final code:
class CatDetail(generic.DetailView):
model = Cat
template_name = 'polls/kitten.html'
Upvotes: 1
Reputation: 131
Alter you views.py
with the following
class CatViews(generic.ListView):
model = Cat
context_object_name = 'cat'
template_name = 'polls/cats.html'
Alter your polls/kitten.html
<h3>{{cat.cat_name}}</h3>
{% for kitty in cat.kittens.all %}
<p>{{ kitty.kitten_type }}</p>
{% endfor %}
EDIT
Additionally, alter you CatDetail
class CatDetail(generic.DetailView):
model = Kitten
context_object_name = 'kittens'
template_name = 'polls/kitten.html'
EDIT 2
Alter your polls/kitten.html
to this.
<h3>{{cat.cat_name}}</h3>
{% for kitty in cat.catdetail.all %}
<p>{{ kitty.kitten_type }}</p>
{% endfor %}
Upvotes: 0
Reputation: 1609
class CatViews(generic.ListView):
model = Cat
template_name = 'polls/cats.html'
context_object_name='cat'
And your polls/cats.html would be like,
<h3>{{cat.cat_name}}</h3>
{% for kitty in cat.kittens.all %}
<p>{{ kitty.kitten_type }}</p>
{% endfor %}
Upvotes: 0