0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Djangoスタートアップ その5(テンプレート編)

0
Last updated at Posted at 2023-02-26

ビューにモデルをインポート

  • template⇔view⇔modelの関係(viewはモデルとテンプレートの橋渡し的な役割)
  • DjangoのTemplateはMVCモデルのViewに該当する
(appName)/views.py
from django.shortcuts import render
from .models import Post★#新たにモデルをインクルード

クエリセットを操作する

(appName)/views.py
from django.shortcuts import render
from django.utils import timezone★#追加
from .models import Post

def post(request):
    posts = Post.objects.all()#posts変数でクエリセットにアクセスできる
    return render(request, '(appname)/post.html', {'posts':posts})★#データを詰め込んでtemplateに返す
補足

{'posts'→templateでアクセスするための名前
:posts→クエリセット}

テンプレートファイルのパス

appName/templates/appName/post_list.html

試しに表示できるか確認↓

appName/templates/appName/post_list.html
{%for post in posts%}★postsはクエリセット
    <div>
        <h2><a href="">{{ post.title }}</a></h2>
    </div>
{% endfor %}

参考記事

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?