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?
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:
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With