class-based view
前回の「Djangoで「Hello World」の表示まで」の続きで、class-based viewでの実装を進めていきます。
まずは「urls.py」ファイルの設定を進めます。
from .views import helloworldfunc
urlpatterns = [
path('admin/', admin.site.urls),
path('helloworldurl/', helloworldfunc),
]
から
from .views import helloworldfunc, HelloWorldClass
urlpatterns = [
path('admin/', admin.site.urls),
path('helloworldurl/', helloworldfunc),
path('helloworldurl2/', HelloWorldClass.as_view()),
]
次に「views.py」ファイルの設定をしていきます
def helloworldfunc(request):
responseobject = HttpResponse('<h1>hello world</h1>')
return responseobject
から
def helloworldfunc(request):
responseobject = HttpResponse('<h1>hello world</h1>')
return responseobject
class HelloWorldClass(TemplateView):
template_name = 'hello.html'
今度は「settings.py」の設定
TEMPLATES = [
{
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
],
},
},
]
から
TEMPLATES = [
{
'DIRS': [BASE_DIR / 'templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
],
},
},
]
最後に一番最初の「hellowrldproject」フォルダー内で「templates」フォルダーを作成し、作成した「templates」フォルダー内で「hello.html」を作成
中身は
<h1>hello world</h1>
$ python manage.py runserver
これで「http://127.0.0.1:8000/helloworldurl2/」にアクセスすると
作成した「hello.html」のサイトが開く