Reputation: 409
I am following this tutorials and created a model and can see the data from admin page. https://djangoforbeginners.com/message-board/
However, i am unable to see the see the posts in the html page. My html pages is inside the template:
Model:
from django.db import models
# Create your models here.
class Post(models.Model):
text = models.TextField()
def __str__(self):
return self.text[:50]
View:
class DiagramsPageView(TemplateView):
posts = Post.objects.all()
template_name = 'diagrams.html'
contex= {'posts': posts}
from .views import DiagramsPageView,
urlpatterns = [
path('diagrams/', DiagramsPageView.as_view(), name='diagrams'),
]
The HTML template page is here
<!-- templates/home.html -->
{% extends 'base.html' %}
{% block content %}
<h1>Diagrams</h1>
<h2>Styling Tables</h2>
<ul>
{{posts}}
</ul>
{% endblock content %}
The HTML page only outputting
Diagrams
Styling Tables
Upvotes: 0
Views: 1179
Reputation: 1860
The variables you declare posts = Post.objects.all()
and contex= {'posts': posts}
are not automatically passed to the context, you have to use get_context_data
class DiagramsPageView(TemplateView):
template_name = 'diagrams.html'
def get_context_data(self, **kwargs):
context = super(DiagramsPageView, self).get_context_data(**kwargs)
context['posts'] = Post.objects.all()
return context
Note: You have to iterate through the object
And your html:
{% block content %}
<h1>Diagrams</h1>
<h2>Styling Tables</h2>
<ul>
{% for post in posts %}
{{ post }}
{% endfor %}
</ul>
Or use ListView
class DiagramsPageView(ListView):
model = Post
template_name = 'diagrams.html'
And your html:
{% block content %}
<h1>Diagrams</h1>
<h2>Styling Tables</h2>
<ul>
{% for post in object_list %}
{{ post }}
{% endfor %}
</ul>
{% endblock content %}
Upvotes: 3