1
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 5 years have passed since last update.

Djangoでウェブアプリ - templateでforループ

Posted at

Djangoを使ってウェブアプリを作ります
templateでforループして出力してみます

  • このページで作成されたDjango環境はここからダウンロード可能です

#1. ファイルを用意します

  • penguinフォルダのurls.pyに以下を追加します
penguin/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('exercise', views.exercise, name='exercise'),
    path('', views.index, name='index'),
]
  • penguinフォルダのviews.pyに以下を記述します
penguin/views.py
from django.shortcuts import render

def index(request):
    return render(request, 'index.html')

def exercise(request):

    e = { '','','','','','','','','','','','' }
    f = []
    f.append('りんご')
    f.append('みかん')
    f.append('バナナ')

    return render(request, 'exercise.html', { 'eto':e, 'fruits':f } )
  • staticフォルダに下記のようなcssを用意します
test.css
.a1 {
  background-color:  #98d98e;
  height: 120px;
  padding: 20px;
}
.b1 {
  background-color:  #e4de8a;
  padding-left: 20px;
  height: 120px;
  text-align:left;
  padding: 20px;
  font-size: 18pt
}
.c1 {
  clear: both;
  background-color:  #cee4ae;
  height: 50px;
  text-align:left;
  font-size: 18pt;
  padding: 20px;
  font-family: Meiryo;
}
.d1 {
  background-color:  #bcbcff;
  height: 200px;
  text-align:left;
  font-size: 18pt;
  padding: 20px;
  font-family: Meiryo;
}
  • penguinフォルダのtemplatesサブフォルダに下記のようなhtmlを用意します
penguin/templates/exercise.html
{% load static %}
<html>
<head>
</head>
<body>
  {% block extrahead %}
  <link href="{% static 'test.css' %}" rel="stylesheet">
  {% endblock %}

  <div class='a1'>
    <h1>テストページ</h1>
  </div>

  <div class='b1'>
      <p><b>干支:</b><br>
      {% for p in eto %}
      {{ p }}
      {% endfor %}
    </p>
  </div>

  <div class='d1'>
    <p>
      <b>果物:</b><br>
      {% for p in fruits %}
      {{ p }}とか<br>
      {% endfor %}
    </p>
  </div>

</body>
</html>

#2. 稼働を確認します

  • python manage.py runserverを実行し、Djangoを起動します
  • ブラウザでlocalhost:8000/exerciseへアクセスし、views.pyからのデータが表示されていることを確認します
スクリーンショット 2018-09-06 9.19.21.png
1
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
1
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?