I have multiple paths in my urls.py
file for app communities
. Here are the two that are causing issues.
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")
For some reason, Django seems to get confused about the order of these two paths. When in the order as shown, Django recognizes that delete_comment
is a path (meaning that in templates using something like communities:delete_comment
does not throw an error when generating the template), but when attempting to navigate to the url, Django keeps catching the post_detail
view and freaks out.
However, when I reverse the order of these two urls, everything works fine. Does order matter? If so, that is rather inconvenient for larger projects.
If any other information is needed, please let me know.
CodePudding user response:
A slug:…>
can also match a sequence of numbers. If you thus visit posts/delete_comment/123
, then Django will try to match it with the URL patterns and starts by the first one. This URL will match the posts/<str:username>/<slug:slug>/
pattern, since it sets username = 'delete_comment'
and slug = '123'
.
Since Django always fires the first URL pattern that matches, if you try to delete a comment, it will thus fire the viewPostDetail
.
What you can do is specify the items in a different order:
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")
]
Another option is to make two URL patterns that do not overlap, for example with:
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")
]