Last update on .

Django 2.0 has some pretty big changes in it. One of the most obvious (and my favorite) is the change in the URL patterns. They have simplified it. And eliminated the complicated use of regular expressions.

I was very excited about this change because I have struggled in the past getting the URL regular expression exactly right.

When I first read about the changes, I thought it meant that it would be a while before I could use Django 2.0 because this change would take a while to proliferate throughout the many, many Python and Django libraries that I like to use. However, the previous url() function is still there so the conversion was much easier than I anticipated. (So far, I have only run into one or two issues using libraries that have not been upgraded and I was able to address those by using the new path() format in my project urls.py file when adding the URL settings for the library.)

Daniel Hepper wrote a nice blog article called Django 2.0 url() to path() Cheatsheet that breaks down the changes in a simplified and easy to understand way. And it comes with a nice cheat sheet!

Here are some of the main points Daniel makes in the article regarding converters:

str - Matches any non-empty string, excluding the path separator, ‘/’. This is the default if a converter isn’t included in the expression. Example: 'best_product_ever!-123.html' Returns a string (str). Equivalent regular expression: [^/]+

int - Matches zero or any positive integer. Example: '1234' Returns an integer (int). Equivalent regular expression: [0-9]+

slug - Matches any slug string consisting of ASCII letters or numbers, plus the hyphen and underscore characters. Returns a string (str). Example: 'building-your-1st-django-site' Equivalent regular expression: [-a-zA-Z0-9_]+

uuid - Matches a formatted UUID. To prevent multiple URLs from mapping to the same page, dashes must be included and letters must be lowercase. Returns a UUID instance (uuid.UUID). Example: '075194d3-6885-417e-a8a8-6c931e272f00' Equivalent regular expression: [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}

path - Matches any non-empty string, including the path separator, ‘/’. This allows you to match against a complete URL path rather than just a segment of a URL path as with str. Example: '/path/to/file' Returns a string (str). Equivalent regular expression: '.+'

Happy coding!

Additional Information about Entry

Comments

No comments yet.

Post your comment