我的urls.py檔案中有多個路徑用于 app communities。這是導致問題的兩個。
path('posts/<str:username>/<slug:slug>',communities_views.viewPostDetail,name="post_detail")
path('posts/delete_comment/<int:comment_id>',communities_views.viewDeleteComment,name="delete_comment")
出于某種原因,Django 似乎對這兩條路徑的順序感到困惑。當按照所示的順序時,Django 識別出這delete_comment是一個路徑(意味著在模板中使用類似的東西communities:delete_comment在生成模板時不會拋出錯誤),但是當嘗試導航到 url 時,Django 不斷捕捉post_detail視圖并嚇壞了。
但是,當我顛倒這兩個 url 的順序時,一切正常。順序重要嗎?如果是這樣,那對于較大的專案來說是相當不方便的。
如果需要任何其他資訊,請告訴我。
uj5u.com熱心網友回復:
Aslug:…>也可以匹配一個數字序列。如果您這樣訪問posts/delete_comment/123,那么 Django 將嘗試將它與 URL 模式匹配并從第一個開始。此 URL 將匹配posts/<str:username>/<slug:slug>/模式,因為它設定了username = 'delete_comment'和slug = '123'。
由于 Django 總是觸發匹配的第一個 URL 模式,如果您嘗試洗掉評論,它將因此觸發viewPostDetail.
您可以做的是以不同的順序指定專案:
urlpatterns = [
# ↓ first try to match with the delete_comment URL pattern
path('posts/delete_comment/<int:comment_id>',communities_views.viewDeleteComment,name="delete_comment"),
path('posts/<str:username>/<slug:slug>',communities_views.viewPostDetail,name="post_detail")
]
另一種選擇是制作兩個不重疊的 URL 模式,例如:
urlpatterns = [
# ↓ non-overlapping URLs
path('posts/<str:username>/view/<slug:slug>',communities_views.viewPostDetail,name="post_detail"),
path('posts/delete_comment/<int:comment_id>',communities_views.viewDeleteComment,name="delete_comment")
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/365349.html
標籤:姜戈 django-urls
