class-based view

前回の「Djangoで「Hello World」の表示まで」の続きで、class-based viewでの実装を進めていきます。

まずは「urls.py」ファイルの設定を進めます。

from django.contrib import admin
from django.urls import path
from .views import helloworldfunc

urlpatterns = [
    path('admin/'admin.site.urls),
    path('helloworldurl/'helloworldfunc),
]

から

from django.contrib import admin
from django.urls import path
from .views import helloworldfuncHelloWorldClass

urlpatterns = [
    path('admin/'admin.site.urls),
    path('helloworldurl/'helloworldfunc),
    path('helloworldurl2/'HelloWorldClass.as_view()),
]

次に「views.py」ファイルの設定をしていきます

from django.http import HttpResponse

def helloworldfunc(request):
    responseobject = HttpResponse('<h1>hello world</h1>')
    return responseobject

から

from django.http import HttpResponse
from django.views.generic import TemplateView

def helloworldfunc(request):
    responseobject = HttpResponse('<h1>hello world</h1>')
    return responseobject

class HelloWorldClass(TemplateView):
    template_name = 'hello.html'

今度は「settings.py」の設定

TEMPLATES = [
    {
        'BACKEND''django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        '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',
            ],
        },
    },
]

から

TEMPLATES = [
    {
        'BACKEND''django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / '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',
            ],
        },
    },
]

最後に一番最初の「hellowrldproject」フォルダー内で「templates」フォルダーを作成し、作成した「templates」フォルダー内で「hello.html」を作成

中身は

<h1>hello world</h1>
$ python manage.py runserver 


これで「http://127.0.0.1:8000/helloworldurl2/」にアクセスすると

作成した「hello.html」のサイトが開く