How to organize URLs?

Let’s say I have urls paths related to user authentication and others related to profiles (but could by about anything). I have all of them in the same app.

Like this:

urlpatterns = [
   #Group profile URLs
    path("profile_list/", views.profile_list, name="profile_list"),
    path("profile/<int:pk>", views.profile, name="profile"),
    path("profile/followers_list/<int:pk>", views.followers_list, name="followers_list"),
    path(
        "profile/followers_list/<int:pk>", views.followers_list, name="followers_list"
    ),
  #Group user authentication URLs
    path("login/", views.login_user, name="login"),
    path("logout/", views.logout_user, name="logout"),
    path("register/", views.register_user, name="register"),
    path("update_user/", views.update_user, name="update_user"),
]

My question is: is it a good desgin pattern to separate and group them like this?

# Group profile URLs
profile_patterns = [
    path("profile_list/", views.profile_list, name="profile_list"),
    path("profile/<int:pk>", views.profile, name="profile"),
    path(
        "profile/followers_list/<int:pk>", views.followers_list, name="followers_list"
    ),
    path("profile/follows_list/<int:pk>", views.follows_list, name="follows_list"),
]

# Group user authentication URLs
user_patterns = [
    path("login/", views.login_user, name="login"),
    path("logout/", views.logout_user, name="logout"),
    path("register/", views.register_user, name="register"),
    path("update_user/", views.update_user, name="update_user"),
]

# Combine all URL patterns into the main urlpatterns
urlpatterns = profile_patterns + user_patterns

Thanks!!

I’d say to do that if it makes things easier / more understandable. It can make sense, especially if each group is much longer. As you probably realise, it doesn’t make any difference to Django which method you prefer.

1 Like

Ultimately, since Django uses urlpatterns, the process of configuring urlpatterns can be done using any method.

I think it would be a good idea to separate the app called profile.

1 Like

I strongly recommend having exactly one urls.py in your project. I switched a year or so back and it’s been a huge improvement. It sounds unintuitive but it’s a big relief to have just one urls.py.

So, you don’t have urls in the apps?

How do you organize your URLS?

I nest them, based on the URL nesting. You can do that with include() without pointing to another module:

path('', include([
    path('foo/', some_view),
])

I don’t think any more organization is needed or helps. A single urls.py isn’t my idea, but something someone mentioned a few times on the Unofficial Django Discord and I tried it and it was obvious after a week that it made life much nicer.

In prod I have my own custom path mapper that improves the syntax a bit, but it’s not a huge improvement over the example above.

2 Likes