1
0

More than 3 years have passed since last update.

DjangoでHTMLファイルを表示させる (初学者がどこまで理解できるか(3))

Last updated at Posted at 2019-10-13

DjangoでHTMLファイルを読み込んでみよう

Djangoでデータベース構築 (初学者がどこまで理解できるか(2)) の続きです。
今回は、ビュー画面にHTMLファイルの内容を表示させてみます。

まずはビューページがクラス毎に表示されることを確認

DjangoでHello world (初学者がどこまで理解できるか(1)) で、
http://127.0.0.1:8000/myapplicationにアクセスした際に、"Hello world"を画面に表示させましたね。

今回は、http://127.0.0.1:8000/myapplication/detailなど、myapplication/以下のURLにアクセスがあった際の、ビューページを表示させます。

#### practice/myapplication/views.py

from django.http import HttpResponse

#index関数にHTTPリクエストがあったら、"Hello, world."のHTTPレスポンスを返す
def index(request):
    return HttpResponse("Hello, world.")

#detail関数にHTTPリクエストがあったら、"This is detail page."のHTTPレスポンスを返す
def detail(request):
    return HttpResponse("This is detail page.")
#### practice/myapplication/urls.py

#path関数を呼び出し
from django.urls import path
from . import views

#URLに、「myapplication/」の後に何も指定しなければ、views.pyに記載の、index関数が呼び出される
#「myapplication/」の後に「detail」が指定されると、views.pyに記載の、detail関数が呼び出される
urlpatterns = [
    path('', views.index, name='index'),
    path('detail/', views.detail, name='detail')
]

開発サーバーを起動すると、http://127.0.0.1:8000/myapplication/detailにアクセスし、http://127.0.0.1:8000/myapplicationと異なるビュー結果であることが確認できます。

index.htmlを表示してみよう

ビューの表示の仕方はわかりました。
それでは続いて、HTMLファイルを表示するにはどうすればよいかを記載していきます。

#### practice/myapplication/
$ mkdir templates
$ mkdir myapplication
$ touch index.html

アプリケーションのフォルダに、templatesmyapplicationindex.htmlを作成します。
views.pyに記載の内容と、htmlファイルの接続口が、templatesフォルダです。

<!-- practice/myapplication/templates/myapplication/index.html -->
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
  </head>
  <body>
    <h1>This is text from HTML<h1>
  </body>
</html>

index.html には、文字列が表示できるようにしておきましょう。

####practice/myapplication/views.py

from django.shortcuts import render

#templatesの内容を読み込んで、HttpResponseする、render関数を使用
def index(request):
    return render(request, 'myapplication/index.html')

views.pyを、上記のように書き換えてみましょう。
この状態で開発サーバーを起動し、http://127.0.0.1:8000/myapplicationにアクセスして、index.htmlの内容が表示されればOKです。

さいごに

次は、データベースの内容を、htmlに反映させたいと思います。

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