第 5 章    部落格系統

▸ 登記 App

blog/settings.py
...
INSTALLED_APPS = [
    ...
    'django.contrib.staticfiles',
    'main',
]
...

▸ 顯示 Hello world 程式

main/views.py
from django.shortcuts import render
from django.http import HttpResponse


def main(request):
    '''
    Show 'Hello world!' in the main page
    '''
    return HttpResponse('Hello world!')

▸ 專案 App 的 URL mapping

blog/urls.py
...
from django.contrib import admin
from django.urls import path, include, re_path
from main import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('main/', include('main.urls', namespace='main')),
    re_path('.*', views.main),
]

main app 的 urls.py

main/urls.py
from django.urls import path
from main import views


app_name = 'main'
urlpatterns = [
    path('', views.main, name='main'),
]

▸ 將 HTML 寫在程式裡

main/views.py
from django.http import HttpResponse


def main(request):
    '''
    Render the main page
    '''
    html = '''
    <!doctype html>
    <html>
    <head>
    <title>部落格</title>
    <meta charset="utf-8">
    </head>
    <body>
    <p>這是 HTML 版的 Hello world!</p>
    </body>
    </html>
    '''
    return HttpResponse(html)

▸ 本章完成專案:blog5.zip