Dynamic Routing with Path Converters
Let's learn how to use path converters with dynamic URL routes in our application.
In the example from the previous lesson, we used the path <age>
, where age
was a variable. Then, the value that we appended in the URL at the place of age
, that value was passed as a string type parameter to the view function age()
. This is the default behavior that the string data type parameters will have. However, we can use a converter to convert this value into another datatype before passing it to the view function. A general use-case for this conversion could be that we want to take the age of the user and apply computations to it to find out if they are eligible for an offer. Therefore, it is appropriate that the age
is an integer
type variable.
Path converters
The following are the path converters available for us to use.
-
str
: Matches any non-empty string, excluding the path separator,'/'
. -
int
: Matches zero or any positive integer. -
slug
: Matches any slug string consisting of ASCII letters or numbers, plus the hyphen and underscore characters. For example,building-your-1st-django-site
. -
uuid
- Matches a formatted UUID. -
path
- Matches any non-empty string, including the path separator,'/'
. This allows us to match against a complete URL path rather than a segment of a URL path, as withstr
.
NOTE: For more details on UUID objects in Python, please refer to their official documentation.
Get hands-on with 1400+ tech skills courses.