- 定義視圖函數
books\views.py:
from django.shortcuts import render
from django.http import HttpResponse
#定義視圖函數
def hello(request):
return HttpResponse("<h1>Hello, world.世界你好.</h1>")
- 修改項目(mydjango) urls.py文件
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('books/', include('books.urls')),
path('admin/', admin.site.urls),
]
- 在books的資料夾新增 urls.py文件
from django.urls import path
from . import views
urlpatterns = [
path('hello/', views.hello, name='hello'),
]
建立完成後的資料如下,執行
python manage.py runserver
開啟瀏覽器,輸入
http://127.0.0.1:8000/books/hello/
URL配置
- urlpatterns: 路由模式列表,通過URL模式映射到視圖
- path函數: 返回urlpatterns元素
定義:path(route, view, kwargs=None, name=None)
route:路由模式,
view:可以是視圖函數、視圖類或include函數返回值
path(”, views.home, name=’home’)
path(”, Home.as_view(), name=’home’)
path(‘blog/’, include(‘blog.urls’)) - include函數:導入其他的模塊,include(‘books.urls’)是導入books.urls模塊