djangoの使い方

本サイトはdjangoで作成しています。
djangoの使用方法についてまとめています。

670 views

テンプレートを使う

前のページで、Hello World!!を表示するプログラムをmysite/maze/views.pyに書いた。

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.


def index(request):
    return HttpResponse("hello world!!")

HttpResponse関数に文字列を渡せばそれがHTMLとして表示されるため、次のように書けば、WEBページを作成できる。
しかし、大半のHTMLは固定であり、これから作成する他の関数も以下のように記述するのは非効率すぎる。

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.


def index(request):
    data = """
            <!DOCTYPE html>
                <html lang="ja">
                    <head>
                        <meta charset="UTF-8">
                        <title>Title</title>
                    </head>
                <body>
                    hello world!!
                </body>
                </html>
            """
    return HttpResponse(data)

そこで、テンプレートを作成する。

まず、mysite/templatesディレクトリを作成する。

mkdir mysite/templates

そして、templatesディレクトリに以下の内容を記述したindex.htmlを作成する。

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    {{data}}
</body>
</html>

8行目の{{data}}だけをviews.index関数で変更する。

templatesファイルのありかを設定するために、
mysite/settings.pyに以下を記述する。

<変更前>
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
<変更後>
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates'), ],

最後にviews.pyのindex関数を次のように変更する。

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.


def index(request):

    return render(request, "index.html", {'data': "hello world!!!"})

http://localhost:8000/mazeにアクセスすると、hello world!!!が出力される。

Page 4 of 14.

前のページ 次のページ



[添付ファイル]


お問い合わせ

プロフィール

マッスル

自己紹介

本サイトの作成者。
趣味:プログラム/水耕栽培/仮想通貨/激辛好き
プログラムは趣味と勉強を兼ねて、のんびり本サイトを作っています。
フレームワークはdjango。
仮想通貨はNEMが好き。
水耕栽培は激辛好きが高じて、キャロライナ・リーパーの栽培にチャレンジ中。

サイト/ブログ

https://www.osumoi-stdio.com/pyarticle/

ツイッター

@darkimpact0626