--- Title: 'templatesを追加・viewを分割 #django' Keywords: - django Author: junshimo2 Web: 'https://mimemo.io/m/p5be8G9nNZoWxkE' --- # templatesを追加・viewを分割 ## プロジェクトの設定 #### project/settings.py ```python TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', #多分下位ディレクトリで処理するので変更しなくていい 'DIRS': [os.path.join(BASE_DIR, 'testapp', 'templates', )], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] ``` ## プロジェクトのURL #### testprj/urls.py ```python from django.contrib import admin from django.urls import include, path from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('testapp.urls')), ] ``` ## アプリケーションのURL #### testapp/urls.py ```python from django.conf.urls import url from django.urls import include, path urlpatterns = [ path('', include('testapp.views.urls')), ] ``` ## viewのURL #### testapp/views/urls.py ```python from django.conf.urls import url from django.urls import include, path from . import views, views2 urlpatterns = [ path('', views.IndexTemplateView.as_view(), ), #クラスのview path('app1/', views.IndexTemplateView.as_view(), ), #関数のview path('app2/', views2.index, name='index'), ] ``` ## クラスのview #### testapp/views/views.py ```python from django.shortcuts import render from django.views.generic import TemplateView class IndexTemplateView(TemplateView): template_name = "index.html" ``` ## 関数のview ```python from django.http import HttpResponse def index(request): return HttpResponse("Hello, World!") ```