我正在遵循本教程并创建了一个模型,可以从管理页面中查看数据。 https://djangoforbeginners.com/message-board/
但是,我看不到html页面中的帖子。我的html页面在模板内:
型号:
from django.db import models
# Create your models here.
class Post(models.Model):
text = models.TextField()
def __str__(self):
return self.text[:50]
查看:
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'),
]
HTML模板页面在这里
<!-- templates/home.html -->
{% extends 'base.html' %}
{% block content %}
<h1>Diagrams</h1>
<h2>Styling Tables</h2>
<ul>
{{posts}}
</ul>
{% endblock content %}
HTML页面仅输出
Diagrams
Styling Tables
答案 0 :(得分:3)
您声明的变量posts = Post.objects.all()
和contex= {'posts': posts}
不会自动传递到上下文,您必须使用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
注意:您必须遍历对象
还有您的html:
{% block content %}
<h1>Diagrams</h1>
<h2>Styling Tables</h2>
<ul>
{% for post in posts %}
{{ post }}
{% endfor %}
</ul>
或使用ListView
class DiagramsPageView(ListView):
model = Post
template_name = 'diagrams.html'
还有您的html:
{% block content %}
<h1>Diagrams</h1>
<h2>Styling Tables</h2>
<ul>
{% for post in object_list %}
{{ post }}
{% endfor %}
</ul>
{% endblock content %}