LoginSignup
1
4

More than 5 years have passed since last update.

Djangoでウェブアプリ - views.pyからhtmlへ出力

Posted at

Djangoを使ってウェブアプリを作ります
views.pyからhtmlへ情報を出力してみます

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

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

def exercise(request):
    now = datetime.now();
    context = {
        'text': 'テストです。',
        'time': now,
    }
    return render(request, 'exercise.html', context)
  • staticフォルダに下記のようなcssを用意します
test.css
.a1 {
  background-color:  #98d98e;
  height: 120px;
  padding: 20px;
}
.b1 {
  background-color:  #e4de8a;
  padding-left: 20px;
  height: 100px;
  text-align:left;
  font-size: 18pt
}
.c1 {
  background-color:  #cee4ae;
  height: 100px;
  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>
        {{ text }}
      </p>
    </div>

    <div class='c1'>
      <p>
        {{ time }}
      </p>
    </div>

  </body>
</html>

2. 稼働を確認します

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

スクリーンショット 2018-09-05 18.37.04.png

1
4
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
4