LoginSignup
1
0

More than 5 years have passed since last update.

Djangoでhtmlを表示する

Posted at

Djangoチュートリアル アプリ作成(1)[DBの設定・ブラウザで開く]の続きです

1. templatesを利用してhtmlをブラウザに表示させる

Djangoチュートリアル アプリ作成(1)[DBの設定・ブラウザで開く]の後に操作を行なってください

ツリー構造

mysite
├── __init__.py
├── __pycache__
├── settings.py
├── templates
│   └── hello.html
├── urls.py
├── views.py
└── wsgi.py

settings.pyの変更

33行目くらいのINSTALLED_APPSを以下のように'hello'を追加します。

settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'hello',
]

templatesディレクトリの作成

mysite直下にtemplatesディレクトリを作成します。
僕の場合は
この中に表示したいhtmlファイルを作成します。
ここでは例として "Hello, World" を表示させてみます。

hello.html
<html>
    <head>
        <meta charset="utf-8">
        <title>Hello, World !!</title>
    </head>
    <body>
        <h1 class="hello">Hello, World !!</h1>
    </body>
</html>

views.pyの変更

views.pyを以下のように変更してください。

views.py
from django.views.generic import TemplateView
from django.shortcuts import render

class IndexTemplateView(TemplateView):
    template_name = "hello.html"

    def get(self, request):
        return render(request, self.template_name)

urls.pyの変更

urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
# views.pyが置いてある場所を指定
from hello.views import IndexTemplateView

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', IndexTemplateView.as_view()),
]

ここまでできたら、以下のコードをターミナルで実行してください。

$ python3 manage.py runserver

そして、以下のURLに行くと
http://127.0.0.1:8000/

スクリーンショット 2019-03-22 17.50.43.png

このように表示されます。

2. views.pyにテキストを書き込んでブラウザに表示させる

Djangoチュートリアル アプリ作成(1)[DBの設定・ブラウザで開く]の後に操作を行なってください

ツリー構造

mysite
├── db.sqlite3
├── hello
│   ├── settings.py
│   ├── urls.py
│   ├── views.py
│   └── wsgi.py
└── manage.py

views.pyの変更

以下のように変更してください。

views.py
from django.http import HttpResponse

def hello_world(req):
    return HttpResponse('Hello, World!')

urls.pyの変更

以下のように変更してください。

urls.py
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
# views.pyが置いてある場所を指定
from hello.views import hello_world

urlpatterns = [
    path('admin/', admin.site.urls),
    path('views_hello/', hello_world),
]

ここまでできたら、以下のコードをターミナルで実行してください。

$ python3 manage.py runserver

そして、以下のURLに行くと
http://127.0.0.1:8000/views_hello/

スクリーンショット 2019-03-22 18.05.10.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