1. 小技巧:指定视图参数默认值
比如访问 /blog/
就会默认到第一页,访问 /blog/page2
时就是第二页
# app/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('blog/', views.page), # num默认是1,显示第一页
path('blog/page<int:num>/', views.page), # 调用同样视图函数,但传入num
]
# app/views.py
def page(request, num=1):
#...
2. 自定义错误页面
# project/urls.py
from django.contrib import admin
from django.urls import path
from app import views # step1. 引入有错误页面视图函数的 views
urlpatterns = [
path('admin/', admin.site.urls),
]
# step2. 增加的条目
handler400 = views.bad_request
handler403 = views.permission_denied
handler404 = views.page_not_found
handler500 = views.error
# app/views.py
def bad_request(request):
return render(request, 'error/400.html')
def permission_denied(request):
return render(request, 'error/403.html')
def page_not_found(request):
return render(request, 'error/404.html')
def error(request):
return render(request, 'error/500.html')
3. URL中相同部分的改进写法
# 原 app/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('<page_slug>-<page_id>/history/', views.history),
path('<page_slug>-<page_id>/edit/', views.edit),
path('<page_slug>-<page_id>/discuss/', views.discuss),
path('<page_slug>-<page_id>/permissions/', views.permissions),
]
# 改进写法:声明共同路径前缀,后面的分组转发
from django.urls import include, path
from . import views
urlpatterns = [
path('<page_slug>-<page_id>/', include([
path('history/', views.history),
path('edit/', views.edit),
path('discuss/', views.discuss),
path('permissions/', views.permissions),
])),
]