urlpatterns conflict <str:username>/

Viewed 49

I have a problem with url paths. As I understand the path users/ is perceived as <str: username>/ named users. Is it possible to solve this problem without creating a new application?

urlpatterns=[
path('',PostList.as_view(), name='index'),
path('<str:username>/new/',News.as_view(), name='new'),
path('<str:username>/', user_posts, name='profile'),
path('<str:username>/<int:post_id>/', post_view, name='tak'),
path('<str:username>/<int:post_id>/add_comment/', comment_add, name='add_comment'),

path('<str:username>/<int:post_id>/edit/', Update.as_view(), name='edit'),
path('users/',user_list,name='user_list'),
path('users/<str:username>/',user_detail,name='user_detail'),

]
1 Answers

You need to define users/ first since if you visit the path /users/, it will "fire" the first URL pattern that matches, in this case the '<str:username>/', not users/`.

So can implement the logic as:

urlpatterns=[
    path('',PostList.as_view(), name='index'),
    #      ↓ first the users/
    path('users/',user_list,name='user_list'),
    path('<str:username>/new/',News.as_view(), name='new'),
    #      ↓ then a path that accepts an arbitrary string
    path('<str:username>/', user_posts, name='profile'),
    path('<str:username>/<int:post_id>/', post_view, name='tak'),
    path('<str:username>/<int:post_id>/add_comment/', comment_add, name='add_comment'),
    path('<str:username>/<int:post_id>/edit/', Update.as_view(), name='edit'),
    path('users/<str:username>/',user_detail,name='user_detail')
]

A consequence of the URL patterns you define is that a user can not use username as username. Therefore it might be better to user users/<str:username>/ for example, since then the patterns do not overlap.

Related