LoginSignup
0
0

More than 5 years have passed since last update.

Djangoでウェブアプリ - templateでif-then条件分岐

Last updated at Posted at 2018-09-06

Djangoを使ってウェブアプリを作ります
templateでif-thenの条件分岐をしてみます

  • このページで作成された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):

    p = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71 }

    return render(request, 'exercise.html', { 'prime': p } )
  • 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
}
  • 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>30以下の素数:</b><br>
      {% for p in prime %}
        {% if p <= 30 %}
          {{ p }}
        {% endif %}
      {% endfor %}
    </p>
  </div>

</body>
</html>

2. 稼働を確認します

  • python manage.py runserverを実行し、Djangoを起動します
  • ブラウザでlocalhost:8000/exerciseへアクセスし、views.pyからのデータが表示されていることを確認します

スクリーンショット 2018-09-06 9.58.14.png

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