I tried to show a model data in html template in django.
My Model:
class Author(models.Model):
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
date_of_birth = models.DateField(blank=True, null=True)
date_of_death = models.DateField(blank=True, null=True)
def get_absolute_url(self):
return reverse('author_detail', args=[str(self.id)])
class Meta():
ordering = ['first_name', 'last_name']
def __str__(self):
return f'{self.first_name} {self.last_name}'
My View:
def author_detail_view(request, pk):
author = get_object_or_404(Author, pk=pk)
return render(request, 'author_detail.html', context={'author_detail': author})
My URL:
path('author/<int:pk>', views.author_detail_view, name='author_detail')
And My Templates View:
{% extends 'base.html' %}
{% block content %}
<h1>Author Detail</h1>
{% for author in author_detail %}
<ul>
<li>Name: {{ author.first_name }} {{ author.last_name }}</li>
<li>Date of Birth: {{ author.date_of_birth }}</li>
</ul>
{% endfor %}
{% endblock %}
But the probelem is, it shoing error that :
TypeError at /author/2
'Author' object is not iterable
Request Method: GET Request URL: http://127.0.0.1:8000/author/2 Django Version: 2.1.5 Exception Type: TypeError Exception Value:
'Author' object is not iterable
Exception Location: /home/pyking/.local/lib/python3.6/site-packages/django/template/defaulttags.py in render, line 165 Python Executable: /usr/bin/python3 Python Version: 3.6.7
The author_detail is a single Author object, so it does not make sense to iterate over it. What would be the elements over which you can iterate?
You can thus render it like:
{% extends 'base.html' %}
{% block content %}
<h1>Author Detail</h1>
<ul>
<li>Name: {{ author_detail.first_name }} {{ author_detail.last_name }}</li>
<li>Date of Birth: {{ author_detail.date_of_birth }}</li>
</ul>
{% endblock %}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With