Simplified URL pattern syntax

Many beginners find the regular expressions special characters such as ^ or $ used in Django's URL patterns to be challenging. Regular expressions are a mini-language in themselves. So a simpler syntax, largely based on Flask, has been accepted as the new and default way of specifying URL patterns.

Instead of using regular expressions, you can specify the URL path directly in the pattern within the path function (which has the same parameters as the earlier URL function). You can also capture named parts of the URL within angle brackets and optionally prefix its data type.

Some examples can explain this better. The following table compares the old and new syntax:

Old (regular expression pattern)

New (simplified pattern)

# Homepage
url(r'^$', IndexView.as_view(), name='home'),
# Homepage
path('', IndexView.as_view(), name='home'),
url(r'^about/$',
AboutView.as_view(),
name='about'),
path('about/',
AboutView.as_view(), name='home'),
url(r'^hello/(?P<name>w+)/$', views.hello_fn),
path('hello/<str:name>/', views.hello_fn),
url(r'^(?P<year>[0-9]{4})/(?P<month>[-w]+)/'
'(?P<day>[0-9]+)/(?P<pk>[0-9]+)/$',
path('<int:year>/<int:month>/'
'<int:day>/<int:pk>/',
The new syntax is not only readable, but better at capturing datatypes such as integers without memorizing their corresponding regular expressions. They will be sent to the view callable after being cast into that datatype. Compare this with regular expressions, which return only string literals.

The following types or path converters are available by default. You can add your own as well:

  • str: Any string that does not have path separator '/' except empty strings. This is the default if no type is specified.
  • int: Any positive integer including zero. Passes an int to the view.
  • slug: Any string made up of a combination of ASCII letters, numbers, - (hyphen), or _ (underscore).
  • uuid: Any uuid, typically represented as 12345678-1234-5678-1234-567812345678. Passes a uuid instance.
  • path: Any string including the path separator / except empty strings.

For more complex matching requirements, you can use regular expressions or register a custom path convertor (recommended if you want to extract non-string data).

We are sending all arguments as keyword arguments. Positional arguments cannot be used in the simplified syntax.

I would recommend using the simplified syntax for its readability and better type checks. But for understanding the majority of existing code bases, you will need to know the regular expression URL pattern syntax as well.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.235.196