1. 小技巧:指定视图参数默认值

比如访问 /blog/ 就会默认到第一页,访问 /blog/page2 时就是第二页

  1. # app/urls.py
  2. from django.urls import path
  3. from . import views
  4. urlpatterns = [
  5. path('blog/', views.page), # num默认是1,显示第一页
  6. path('blog/page<int:num>/', views.page), # 调用同样视图函数,但传入num
  7. ]
  8. # app/views.py
  9. def page(request, num=1):
  10. #...

2. 自定义错误页面

  1. # project/urls.py
  2. from django.contrib import admin
  3. from django.urls import path
  4. from app import views # step1. 引入有错误页面视图函数的 views
  5. urlpatterns = [
  6. path('admin/', admin.site.urls),
  7. ]
  8. # step2. 增加的条目
  9. handler400 = views.bad_request
  10. handler403 = views.permission_denied
  11. handler404 = views.page_not_found
  12. handler500 = views.error
  13. # app/views.py
  14. def bad_request(request):
  15. return render(request, 'error/400.html')
  16. def permission_denied(request):
  17. return render(request, 'error/403.html')
  18. def page_not_found(request):
  19. return render(request, 'error/404.html')
  20. def error(request):
  21. return render(request, 'error/500.html')

3. URL中相同部分的改进写法

  1. # 原 app/urls.py
  2. from django.urls import path
  3. from . import views
  4. urlpatterns = [
  5. path('<page_slug>-<page_id>/history/', views.history),
  6. path('<page_slug>-<page_id>/edit/', views.edit),
  7. path('<page_slug>-<page_id>/discuss/', views.discuss),
  8. path('<page_slug>-<page_id>/permissions/', views.permissions),
  9. ]
  10. # 改进写法:声明共同路径前缀,后面的分组转发
  11. from django.urls import include, path
  12. from . import views
  13. urlpatterns = [
  14. path('<page_slug>-<page_id>/', include([
  15. path('history/', views.history),
  16. path('edit/', views.edit),
  17. path('discuss/', views.discuss),
  18. path('permissions/', views.permissions),
  19. ])),
  20. ]