Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Django 3.2.6: Path order in app urls.py related to 404

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")

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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")
]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading