DjangoアプリのURLルーティングと、viewやtemplatesなんかの関係性及びファイル構成がなかなか覚えられないのでメモ。
実行環境はローカルで、settings.pyのDEBUGはTrue。
Djangoのプロジェクト
sampleというフォルダにpython仮想環境を作成し、Djangoのプロジェクトを作っています。
自作アプリ名はapp。
models.pyとか他のファイルは省略。
templatesとstaticの配下にもう一つ同名のappディレクトリをかませる理由は、なんか複数アプリがある場合、名前かぶり問題があるみたいなので。
デメリットはハードコーディングぎみになること?
manage.pyと同じ階層にtemplatesを置くやり方も多く見かけましたが、今回はアプリごとに分けるやり方で行っています。
Django テンプレート(templates)を利用する
[django]templatesディレクトリを配置する場所(ベストプラクティスを考えてみた) - dackdive's blog
1.project/project/urls.py
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('app.urls')), ]
クラスベースビューの場合
2.project/app/urls.py
from django.urls import path from . import views urlpatterns = [ path('', views.TestView.as_view()), ]
3.project/app/views.py
from django.views.generic import TemplateView class TestView(TemplateView): template_name = 'app/index.html'
関数ベースビューの場合(もうあんまり使わないらしい)
2.project/app/urls.py
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ]
3.project/app/views.py
from django.shortcuts import render def index(request): return render(request, 'app/index.html')
4.project/app/templates/app/index.html
{% load static %} <html> <head> <link rel="stylesheet" type="text/css" href="{% static 'app/css/test.css' %}"> <meta charset="utf-8"> <title>test</title> </head> <body> <h1>this is test.</h1> </body> </html>
5.project/app/static/app/css/test.css
h1{ color:#F00; font-size: 22px; }
サーバーを起動するとこんな感じ。
[実行環境]
Win10
python 3.7.7(64bit)
Django 3.0.7