KAMEYA_WORKS
アプリディレクトリ hello
の中に以下のような構成でフォルダとファイルを作成します。
hello/
├── static/
│ └── hello/
│ └── style.css
style.css
)body {
font-family: sans-serif;
background-color: #f0f8ff;
text-align: center;
padding-top: 50px;
}
h1 {
color: #333;
}
button {
padding: 10px 20px;
font-size: 16px;
margin-top: 20px;
cursor: pointer;
}
index.html
)index.html
に CSS の読み込みを追加し、ボタンを配置します。
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>こんにちは</title>
<link rel="stylesheet" href="/static/hello/style.css">
</head>
<body>
<h1></h1>
<form action="{% url 'hello:next' %}">
<button type="submit">次のページへ</button>
</form>
</body>
</html>
next.html
hello/
├── templates/
│ └── hello/
│ ├── index.html
│ └── next.html
next.html の中身:
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>次のページ</title>
<link rel="stylesheet" href="/static/hello/style.css">
</head>
<body>
<h1>これは次のページです!</h1>
<a href="{% url 'hello:home' %}"><button>戻る</button></a>
</body>
</html>
views.py
from django.shortcuts import render
def say_hello(request):
context = {'message': 'こんにちは、Djangoの世界へようこそ!'}
return render(request, 'hello/index.html', context)
def next_page(request):
return render(request, 'hello/next.html')
hello/urls.py
名前付きURLパターンを使ってテンプレートからリンクします。
from django.urls import path
from . import views
app_name = 'hello'
urlpatterns = [
path('', views.say_hello, name='home'),
path('next/', views.next_page, name='next'),
]
python manage.py runserver
http://127.0.0.1:8000/
にアクセスし、スタイルが適用された「こんにちは」画面が表示されていることを確認。このステップでは、以下の技術を学びました:
この経験を通じて、Webアプリの「見た目」と「操作性」も自分で作れることが分かってきたはずです。次のステップでは、フォーム入力やデータの保存にチャレンジしてみましょう。