Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should I use 'path' over 're_path'?

Here is an example from Django Docs:

from django.urls import include, path

urlpatterns = [
    path('index/', views.index, name='main-view'),
    path('bio/<username>/', views.bio, name='bio'),
    ...
]
from django.urls import include, re_path

urlpatterns = [
    re_path(r'^index/$', views.index, name='index'),
    re_path(r'^bio/(?P<username>\w+)/$', views.bio, name='bio'),
    ...
]

From my understanding path syntax is more readable and offers the angle brackets that can catch information from the URL and convert a type.

Should I use re_path only when I need a regular expression and use path for all other cases?

like image 345
Yuri Kots Avatar asked Mar 21 '19 17:03

Yuri Kots


2 Answers

re_path is an implementation of the 'old' way of handling urls, which was previously (version <2) done by url from django.conf.urls.

See the paragraph in Django 2.0 release notes about this.

This being said, I recommend using path whenever you can!

The reasons I see:

  1. path was introduced with the goal of making things simpler, which is clearly the direction the Django devs want to go. So, when using path you are following this direction, thus minimizing the risk of having to adapt your codebase to new changes.

  2. While path is not just a result of an attempt of making things simpler, it actually really does make things simpler and more readable, which is a good reason alone to why path should be preferred if both choices are an option.

Now re_path exists for reasons, so there are cases when using re_path might still be a better option. One scenario is clearly when require very customized converter and reach the limit of what is feasible with custom converters for 'path'. Yet another scenario to use re_path could be when upgrading a system with rather complex url-converters form a Django 1.x to a 2.x: Simply replacing the url with re_path commands can be much more time-efficient and thus be a desirable approach.

like image 184
jojo Avatar answered Nov 10 '22 00:11

jojo


You got it. The newer path syntax makes for much cleaner URL patterns. You can write your own path converters, too, so that more of your paths can use path instead of re_path.

like image 25
Franey Avatar answered Nov 09 '22 22:11

Franey