class Blog(models.Model):
title = models.CharField(max_length=200)
content = models.TextField(blank=True)
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Meta:
db_table = 'blogs'
ListViewの継承
views.pyでListViewを継承して,viewclassを作成します
from django.views.generic import ListView #追加
from .models import Blog #読み込みたいモデル
class BlogListView(ListView):
model = Blog
template_name = 'blog/blog.html' #表示したいHTML
context_object_name = 'results' #お好きな名前をどうぞ
model データベースのテーブル名
template_name 表示したいHTML
context_object_name HTML上で扱うオブジェクト名
ListViewを表示するHTMLの作成
ListViewで指定したtemplate名でhtmlファイルを作成しましょう
templates
blog
base.html
blog.html
オブジェクトの取り出し方はfor文です
{%%}の中にpythonの構文を記述して最後に{% endfor %}を記述してください
オブジェクトの各カラムは{{オブジェクト.カラム名}}で取り出せます
{% block main %}
<div class="text-center mb-5">
<h1 class="display-3 mb-5">はやてれおのBlog</h1>
<p class="text-muted fs-3">Blogの記事一覧</p>
</div>
<div>
{% for result in results %}
<h4>{{ result.title }}</h4>
<p>{{ result.created_at }}</p>
<p class="lead">{{ result.content }}</p>
{% endfor %}
</div>
{% endblock %}
コメント