Regular expression URL pattern syntax

URL regular expression patterns can sometimes look like a confusing mass of punctuation marks. However, like most things in Django, it is just regular Python.

It can be easily understood by looking at the regular expression patterns' two functions: matching and extraction.

The first part is easy. If you need to match a path such as /year/1980/, then just use a regular expression such as ^year/\d+/ (here \d stands for a single digit from 0 to 9). Ignore the leading slash, as it gets eaten up.

The second part is interesting because, in our example, there are two ways of extracting the year (that is, 1980), which is required by the view.

The simplest way is to put a parenthesis around every group of values ...

Get Django Design Patterns and Best Practices - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.