So, to recap, this view function returns an HTML page that includes the current date and time. But how do we tell Django to use this code? That’s where URLconfs come in.
If, at this point, you ran python manage.py runserver again, you’d still see the “Welcome to Django” message, with no trace of our “Hello world” view anywhere. That’s because our mysite project doesn’t yet know about the hello view; we need to tell Django explicitly that we’re activating this view at a particular URL.
Continuing our previous analogy of publishing static HTML files, at this point we’ve created the HTML file but haven’t uploaded it to a directory on the server yet. To hook a view function to a particular URL with Django, we use a URLconf.
A URLconf is like a table of contents for your Django-powered web site. Basically, it’s a mapping between URLs and the view functions that should be called for those URLs. It’s how you tell Django, “For this URL, call this code, and for that URL, call that code.” For example, when somebody visits the URL /foo/, call the view function foo_view(), which lives in the Python module views.py.
When you executed django-admin startproject in the previous chapter, the script created a URLconf for you automatically: the file urls.py. By default, it looks something like this:
"""mysite URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^If we ignore the documentation comments at the top of the file, here’s the essence of a URLconf:
from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls),]Let’s step through this code one line at a time:
- The first line imports two functions from the django.conf.urls module: include which allows you to include a full Python import path to another URLconf module, and url which uses a regular expression to pattern match the URL in your browser to a module in your Django project.
- The second line calls the function admin from the django.contrib module. This function is called by the include function to load the URLs for the Django admin site.
- The third line is urlpatterns – a simple list of url() instances.
The main thing to note here is the variable urlpatterns, which Django expects to find in your URLconf module. This variable defines the mapping between URLs and the code that handles those URLs. To add a URL and view to the URLconf, just add a mapping between a URL pattern and the view function. Here’s how to hook in our hello view:
from django.conf.urls import url from django.contrib import admin from mysite.views import hello urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^hello/We made two changes here:
- First, we imported the hello view from its module – mysite/views.py, which translates into mysite.views in Python import syntax. (This assumes mysite/views.py is on your Python path.)
- Next, we added the line url(r'^hello/$', hello), to urlpatterns. This line is referred to as a URLpattern. The url() function tells Django how to handle the URL that you are configuring. The first argument is a pattern-matching string (a regular expression; more on this in a bit) and the second argument is the view function to use for that pattern. url() can take other optional arguments as well.
One more important detail we’ve introduced here is that ‘r‘ character in front of the regular expression string. This tells Python that the string is a “raw string” – its contents should not interpret backslashes. In normal Python strings, backslashes are used for escaping special characters – such as in the string “\n“, which is a one-character string containing a newline.
When you add the r to make it a raw string, Python does not apply its backslash escaping – so, “r'\n'” is a two-character string containing a literal backslash and a lowercase “n”. There’s a natural collision between Python’s usage of backslashes and the backslashes that are found in regular expressions, so it’s best practice to use raw strings any time you’re defining a regular expression in Django.
In a nutshell, we just told Django that any request to the URL /hello/ should be handled by the hello view function. It’s worth discussing the syntax of this URLpattern, as it may not be immediately obvious. Although we want to match the URL /hello/, the pattern looks a bit different than that. Here’s why:
- Django removes the slash from the front of every incoming URL before it checks the URLpatterns. This means that our URLpattern doesn’t include the leading slash in /hello/. At first, this may seem unintuitive, but this requirement simplifies things – such as the inclusion of URLconfs within other URLconfs.
- The pattern includes a caret (^) and a dollar sign ($). These are regular expression characters that have a special meaning: the caret means “require that the pattern matches the start of the string,” and the dollar sign means “require that the pattern matches the end of the string.”
This concept is best explained by example. If we had instead used the pattern ^hello/(without a dollar sign at the end), then any URL starting with /hello/ would match, such as /hello/foo and /hello/bar, not just /hello/.
Similarly, if we had left off the initial caret character (i.e., hello/$), Django would match any URL that ends with hello/, such as /foo/bar/hello/. If we had simply used hello/, without a caret or dollar sign, then any URL containing hello/ would match, such as /foo/hello/bar.Thus, we use both the caret and dollar sign to ensure that only the URL /hello/ matches – nothing more, nothing less.
Most of your URLpatterns will start with carets and end with dollar signs, but it’s nice to have the flexibility to perform more sophisticated matches. You may be wondering what happens if someone requests the URL /hello (that is, without a trailing slash). Because our URLpattern requires a trailing slash, that URL would not match. However, by default, any request to a URL that doesn’t match a URLpattern and doesn’t end with a slash will be redirected to the same URL with a trailing slash (This is regulated by the APPEND_SLASH Django setting, which is covered in Appendix D).
The other thing to note about this URLconf is that we’ve passed the hello view function as an object without calling the function. This is a key feature of Python (and other dynamic languages): functions are first-class objects, which means you can pass them around just like any other variables. Cool stuff, eh?
To test our changes to the URLconf, start the Django development server, by running the command python manage.py runserver from within your Python virtual environment. (If you left it running, that’s fine, too. The development server automatically detects changes to your Python code and reloads as necessary, so you don’t have to restart the server between changes.)
The server is running at the address http://127.0.0.1:8000/, so open up a web browser and go to http://127.0.0.1:8000/hello/. You should see the text “Hello world” – the output of your Django view, as below
Regular Expressions
Regular expressions (or regexes) are a compact way of specifying patterns in text. While Django URLconfs allow arbitrary regexes for powerful URL-matching capability, you’ll probably use only a few regex patterns in practice. Here’s a small selection of common patterns:
Symbol | Matches |
. (dot) | Any character |
\d | Any digit |
[A-Z] | Any character, A-Z (uppercase) |
[a-z] | Any character, a-z (lowercase) |
[A-Za-z] | Any character, a-z (case insensitive) |
+ | One or more of the previous expression (e.g., \d+ matches one or more digit) |
[^/]+ | All characters except forward slash |
? | Zero or more of the previous expression (e.g., \d* matches zero or more digits) |
{1,3} | Between one and three (inclusive) of the previous expression |
If we ignore the documentation comments at the top of the file, here’s the essence of a URLconf:
Let’s step through this code one line at a time:
- The first line imports two functions from the django.conf.urls module: include which allows you to include a full Python import path to another URLconf module, and url which uses a regular expression to pattern match the URL in your browser to a module in your Django project.
- The second line calls the function admin from the django.contrib module. This function is called by the include function to load the URLs for the Django admin site.
- The third line is urlpatterns – a simple list of url() instances.
The main thing to note here is the variable urlpatterns, which Django expects to find in your URLconf module. This variable defines the mapping between URLs and the code that handles those URLs. To add a URL and view to the URLconf, just add a mapping between a URL pattern and the view function. Here’s how to hook in our hello view:
We made two changes here:
- First, we imported the hello view from its module – mysite/views.py, which translates into mysite.views in Python import syntax. (This assumes mysite/views.py is on your Python path.)
- Next, we added the line url(r'^hello/$', hello), to urlpatterns. This line is referred to as a URLpattern. The url() function tells Django how to handle the URL that you are configuring. The first argument is a pattern-matching string (a regular expression; more on this in a bit) and the second argument is the view function to use for that pattern. url() can take other optional arguments as well.
One more important detail we’ve introduced here is that ‘r‘ character in front of the regular expression string. This tells Python that the string is a “raw string” – its contents should not interpret backslashes. In normal Python strings, backslashes are used for escaping special characters – such as in the string “\n“, which is a one-character string containing a newline.
When you add the r to make it a raw string, Python does not apply its backslash escaping – so, “r'\n'” is a two-character string containing a literal backslash and a lowercase “n”. There’s a natural collision between Python’s usage of backslashes and the backslashes that are found in regular expressions, so it’s best practice to use raw strings any time you’re defining a regular expression in Django.
In a nutshell, we just told Django that any request to the URL /hello/ should be handled by the hello view function. It’s worth discussing the syntax of this URLpattern, as it may not be immediately obvious. Although we want to match the URL /hello/, the pattern looks a bit different than that. Here’s why:
- Django removes the slash from the front of every incoming URL before it checks the URLpatterns. This means that our URLpattern doesn’t include the leading slash in /hello/. At first, this may seem unintuitive, but this requirement simplifies things – such as the inclusion of URLconfs within other URLconfs.
- The pattern includes a caret (^) and a dollar sign ($). These are regular expression characters that have a special meaning: the caret means “require that the pattern matches the start of the string,” and the dollar sign means “require that the pattern matches the end of the string.”
This concept is best explained by example. If we had instead used the pattern ^hello/(without a dollar sign at the end), then any URL starting with /hello/ would match, such as /hello/foo and /hello/bar, not just /hello/.
Similarly, if we had left off the initial caret character (i.e., hello/$), Django would match any URL that ends with hello/, such as /foo/bar/hello/. If we had simply used hello/, without a caret or dollar sign, then any URL containing hello/ would match, such as /foo/hello/bar.Thus, we use both the caret and dollar sign to ensure that only the URL /hello/ matches – nothing more, nothing less.
Most of your URLpatterns will start with carets and end with dollar signs, but it’s nice to have the flexibility to perform more sophisticated matches. You may be wondering what happens if someone requests the URL /hello (that is, without a trailing slash). Because our URLpattern requires a trailing slash, that URL would not match. However, by default, any request to a URL that doesn’t match a URLpattern and doesn’t end with a slash will be redirected to the same URL with a trailing slash (This is regulated by the APPEND_SLASH Django setting, which is covered in Appendix D).
The other thing to note about this URLconf is that we’ve passed the hello view function as an object without calling the function. This is a key feature of Python (and other dynamic languages): functions are first-class objects, which means you can pass them around just like any other variables. Cool stuff, eh?
To test our changes to the URLconf, start the Django development server, by running the command python manage.py runserver from within your Python virtual environment. (If you left it running, that’s fine, too. The development server automatically detects changes to your Python code and reloads as necessary, so you don’t have to restart the server between changes.)
The server is running at the address http://127.0.0.1:8000/, so open up a web browser and go to http://127.0.0.1:8000/hello/. You should see the text “Hello world” – the output of your Django view, as below
Regular Expressions
Regular expressions (or regexes) are a compact way of specifying patterns in text. While Django URLconfs allow arbitrary regexes for powerful URL-matching capability, you’ll probably use only a few regex patterns in practice. Here’s a small selection of common patterns:
Symbol | Matches |
. (dot) | Any character |
\d | Any digit |
[A-Z] | Any character, A-Z (uppercase) |
[a-z] | Any character, a-z (lowercase) |
[A-Za-z] | Any character, a-z (case insensitive) |
+ | One or more of the previous expression (e.g., \d+ matches one or more digit) |
[^/]+ | All characters except forward slash |
? | Zero or more of the previous expression (e.g., \d* matches zero or more digits) |
{1,3} | Between one and three (inclusive) of the previous expression |
If we ignore the documentation comments at the top of the file, here’s the essence of a URLconf:
Let’s step through this code one line at a time:
- The first line imports two functions from the django.conf.urls module: include which allows you to include a full Python import path to another URLconf module, and url which uses a regular expression to pattern match the URL in your browser to a module in your Django project.
- The second line calls the function admin from the django.contrib module. This function is called by the include function to load the URLs for the Django admin site.
- The third line is urlpatterns – a simple list of url() instances.
The main thing to note here is the variable urlpatterns, which Django expects to find in your URLconf module. This variable defines the mapping between URLs and the code that handles those URLs. To add a URL and view to the URLconf, just add a mapping between a URL pattern and the view function. Here’s how to hook in our hello view:
We made two changes here:
- First, we imported the hello view from its module – mysite/views.py, which translates into mysite.views in Python import syntax. (This assumes mysite/views.py is on your Python path.)
- Next, we added the line url(r'^hello/$', hello), to urlpatterns. This line is referred to as a URLpattern. The url() function tells Django how to handle the URL that you are configuring. The first argument is a pattern-matching string (a regular expression; more on this in a bit) and the second argument is the view function to use for that pattern. url() can take other optional arguments as well.
One more important detail we’ve introduced here is that ‘r‘ character in front of the regular expression string. This tells Python that the string is a “raw string” – its contents should not interpret backslashes. In normal Python strings, backslashes are used for escaping special characters – such as in the string “\n“, which is a one-character string containing a newline.
When you add the r to make it a raw string, Python does not apply its backslash escaping – so, “r'\n'” is a two-character string containing a literal backslash and a lowercase “n”. There’s a natural collision between Python’s usage of backslashes and the backslashes that are found in regular expressions, so it’s best practice to use raw strings any time you’re defining a regular expression in Django.
In a nutshell, we just told Django that any request to the URL /hello/ should be handled by the hello view function. It’s worth discussing the syntax of this URLpattern, as it may not be immediately obvious. Although we want to match the URL /hello/, the pattern looks a bit different than that. Here’s why:
- Django removes the slash from the front of every incoming URL before it checks the URLpatterns. This means that our URLpattern doesn’t include the leading slash in /hello/. At first, this may seem unintuitive, but this requirement simplifies things – such as the inclusion of URLconfs within other URLconfs.
- The pattern includes a caret (^) and a dollar sign ($). These are regular expression characters that have a special meaning: the caret means “require that the pattern matches the start of the string,” and the dollar sign means “require that the pattern matches the end of the string.”
This concept is best explained by example. If we had instead used the pattern ^hello/(without a dollar sign at the end), then any URL starting with /hello/ would match, such as /hello/foo and /hello/bar, not just /hello/.
Similarly, if we had left off the initial caret character (i.e., hello/$), Django would match any URL that ends with hello/, such as /foo/bar/hello/. If we had simply used hello/, without a caret or dollar sign, then any URL containing hello/ would match, such as /foo/hello/bar.Thus, we use both the caret and dollar sign to ensure that only the URL /hello/ matches – nothing more, nothing less.
Most of your URLpatterns will start with carets and end with dollar signs, but it’s nice to have the flexibility to perform more sophisticated matches. You may be wondering what happens if someone requests the URL /hello (that is, without a trailing slash). Because our URLpattern requires a trailing slash, that URL would not match. However, by default, any request to a URL that doesn’t match a URLpattern and doesn’t end with a slash will be redirected to the same URL with a trailing slash (This is regulated by the APPEND_SLASH Django setting, which is covered in Appendix D).
The other thing to note about this URLconf is that we’ve passed the hello view function as an object without calling the function. This is a key feature of Python (and other dynamic languages): functions are first-class objects, which means you can pass them around just like any other variables. Cool stuff, eh?
To test our changes to the URLconf, start the Django development server, by running the command python manage.py runserver from within your Python virtual environment. (If you left it running, that’s fine, too. The development server automatically detects changes to your Python code and reloads as necessary, so you don’t have to restart the server between changes.)
The server is running at the address http://127.0.0.1:8000/, so open up a web browser and go to http://127.0.0.1:8000/hello/. You should see the text “Hello world” – the output of your Django view, as below
Regular Expressions
Regular expressions (or regexes) are a compact way of specifying patterns in text. While Django URLconfs allow arbitrary regexes for powerful URL-matching capability, you’ll probably use only a few regex patterns in practice. Here’s a small selection of common patterns:
Symbol | Matches |
. (dot) | Any character |
\d | Any digit |
[A-Z] | Any character, A-Z (uppercase) |
[a-z] | Any character, a-z (lowercase) |
[A-Za-z] | Any character, a-z (case insensitive) |
+ | One or more of the previous expression (e.g., \d+ matches one or more digit) |
[^/]+ | All characters except forward slash |
? | Zero or more of the previous expression (e.g., \d* matches zero or more digits) |
{1,3} | Between one and three (inclusive) of the previous expression |
We made two changes here:
- First, we imported the hello view from its module – mysite/views.py, which translates into mysite.views in Python import syntax. (This assumes mysite/views.py is on your Python path.)
- Next, we added the line url(r’^hello/$’, hello), to urlpatterns. This line is referred to as a URLpattern. The url() function tells Django how to handle the URL that you are configuring. The first argument is a pattern-matching string (a regular expression; more on this in a bit) and the second argument is the view function to use for that pattern. url() can take other optional arguments as well.
One more important detail we’ve introduced here is that ‘r‘ character in front of the regular expression string. This tells Python that the string is a “raw string” – its contents should not interpret backslashes. In normal Python strings, backslashes are used for escaping special characters – such as in the string “\n“, which is a one-character string containing a newline.
When you add the r to make it a raw string, Python does not apply its backslash escaping – so, “r’\n’” is a two-character string containing a literal backslash and a lowercase “n”. There’s a natural collision between Python’s usage of backslashes and the backslashes that are found in regular expressions, so it’s best practice to use raw strings any time you’re defining a regular expression in Django.
In a nutshell, we just told Django that any request to the URL /hello/ should be handled by the hello view function. It’s worth discussing the syntax of this URLpattern, as it may not be immediately obvious. Although we want to match the URL /hello/, the pattern looks a bit different than that. Here’s why:
- Django removes the slash from the front of every incoming URL before it checks the URLpatterns. This means that our URLpattern doesn’t include the leading slash in /hello/. At first, this may seem unintuitive, but this requirement simplifies things – such as the inclusion of URLconfs within other URLconfs.
- The pattern includes a caret (^) and a dollar sign ($). These are regular expression characters that have a special meaning: the caret means “require that the pattern matches the start of the string,” and the dollar sign means “require that the pattern matches the end of the string.”
This concept is best explained by example. If we had instead used the pattern ^hello/(without a dollar sign at the end), then any URL starting with /hello/ would match, such as /hello/foo and /hello/bar, not just /hello/.
Similarly, if we had left off the initial caret character (i.e., hello/$), Django would match any URL that ends with hello/, such as /foo/bar/hello/. If we had simply used hello/, without a caret or dollar sign, then any URL containing hello/ would match, such as /foo/hello/bar.Thus, we use both the caret and dollar sign to ensure that only the URL /hello/ matches – nothing more, nothing less.
Most of your URLpatterns will start with carets and end with dollar signs, but it’s nice to have the flexibility to perform more sophisticated matches. You may be wondering what happens if someone requests the URL /hello (that is, without a trailing slash). Because our URLpattern requires a trailing slash, that URL would not match. However, by default, any request to a URL that doesn’t match a URLpattern and doesn’t end with a slash will be redirected to the same URL with a trailing slash (This is regulated by the APPEND_SLASH Django setting, which is covered in Appendix D).
The other thing to note about this URLconf is that we’ve passed the hello view function as an object without calling the function. This is a key feature of Python (and other dynamic languages): functions are first-class objects, which means you can pass them around just like any other variables. Cool stuff, eh?
To test our changes to the URLconf, start the Django development server, by running the command python manage.py runserver from within your Python virtual environment. (If you left it running, that’s fine, too. The development server automatically detects changes to your Python code and reloads as necessary, so you don’t have to restart the server between changes.)
The server is running at the address http://127.0.0.1:8000/, so open up a web browser and go to http://127.0.0.1:8000/hello/. You should see the text “Hello world” – the output of your Django view, as below
Regular Expressions
Regular expressions (or regexes) are a compact way of specifying patterns in text. While Django URLconfs allow arbitrary regexes for powerful URL-matching capability, you’ll probably use only a few regex patterns in practice. Here’s a small selection of common patterns:
Symbol | Matches |
. (dot) | Any character |
\d | Any digit |
[A-Z] | Any character, A-Z (uppercase) |
[a-z] | Any character, a-z (lowercase) |
[A-Za-z] | Any character, a-z (case insensitive) |
+ | One or more of the previous expression (e.g., \d+ matches one or more digit) |
[^/]+ | All characters except forward slash |
? | Zero or more of the previous expression (e.g., \d* matches zero or more digits) |
{1,3} | Between one and three (inclusive) of the previous expression |
If we ignore the documentation comments at the top of the file, here’s the essence of a URLconf:
Let’s step through this code one line at a time:
- The first line imports two functions from the django.conf.urls module: include which allows you to include a full Python import path to another URLconf module, and url which uses a regular expression to pattern match the URL in your browser to a module in your Django project.
- The second line calls the function admin from the django.contrib module. This function is called by the include function to load the URLs for the Django admin site.
- The third line is urlpatterns – a simple list of url() instances.
The main thing to note here is the variable urlpatterns, which Django expects to find in your URLconf module. This variable defines the mapping between URLs and the code that handles those URLs. To add a URL and view to the URLconf, just add a mapping between a URL pattern and the view function. Here’s how to hook in our hello view:
We made two changes here:
- First, we imported the hello view from its module – mysite/views.py, which translates into mysite.views in Python import syntax. (This assumes mysite/views.py is on your Python path.)
- Next, we added the line url(r’^hello/$’, hello), to urlpatterns. This line is referred to as a URLpattern. The url() function tells Django how to handle the URL that you are configuring. The first argument is a pattern-matching string (a regular expression; more on this in a bit) and the second argument is the view function to use for that pattern. url() can take other optional arguments as well.
One more important detail we’ve introduced here is that ‘r‘ character in front of the regular expression string. This tells Python that the string is a “raw string” – its contents should not interpret backslashes. In normal Python strings, backslashes are used for escaping special characters – such as in the string “\n“, which is a one-character string containing a newline.
When you add the r to make it a raw string, Python does not apply its backslash escaping – so, “r’\n’” is a two-character string containing a literal backslash and a lowercase “n”. There’s a natural collision between Python’s usage of backslashes and the backslashes that are found in regular expressions, so it’s best practice to use raw strings any time you’re defining a regular expression in Django.
In a nutshell, we just told Django that any request to the URL /hello/ should be handled by the hello view function. It’s worth discussing the syntax of this URLpattern, as it may not be immediately obvious. Although we want to match the URL /hello/, the pattern looks a bit different than that. Here’s why:
- Django removes the slash from the front of every incoming URL before it checks the URLpatterns. This means that our URLpattern doesn’t include the leading slash in /hello/. At first, this may seem unintuitive, but this requirement simplifies things – such as the inclusion of URLconfs within other URLconfs.
- The pattern includes a caret (^) and a dollar sign ($). These are regular expression characters that have a special meaning: the caret means “require that the pattern matches the start of the string,” and the dollar sign means “require that the pattern matches the end of the string.”
This concept is best explained by example. If we had instead used the pattern ^hello/(without a dollar sign at the end), then any URL starting with /hello/ would match, such as /hello/foo and /hello/bar, not just /hello/.
Similarly, if we had left off the initial caret character (i.e., hello/$), Django would match any URL that ends with hello/, such as /foo/bar/hello/. If we had simply used hello/, without a caret or dollar sign, then any URL containing hello/ would match, such as /foo/hello/bar.Thus, we use both the caret and dollar sign to ensure that only the URL /hello/ matches – nothing more, nothing less.
Most of your URLpatterns will start with carets and end with dollar signs, but it’s nice to have the flexibility to perform more sophisticated matches. You may be wondering what happens if someone requests the URL /hello (that is, without a trailing slash). Because our URLpattern requires a trailing slash, that URL would not match. However, by default, any request to a URL that doesn’t match a URLpattern and doesn’t end with a slash will be redirected to the same URL with a trailing slash (This is regulated by the APPEND_SLASH Django setting, which is covered in Appendix D).
The other thing to note about this URLconf is that we’ve passed the hello view function as an object without calling the function. This is a key feature of Python (and other dynamic languages): functions are first-class objects, which means you can pass them around just like any other variables. Cool stuff, eh?
To test our changes to the URLconf, start the Django development server, by running the command python manage.py runserver from within your Python virtual environment. (If you left it running, that’s fine, too. The development server automatically detects changes to your Python code and reloads as necessary, so you don’t have to restart the server between changes.)
The server is running at the address http://127.0.0.1:8000/, so open up a web browser and go to http://127.0.0.1:8000/hello/. You should see the text “Hello world” – the output of your Django view, as below
Regular Expressions
Regular expressions (or regexes) are a compact way of specifying patterns in text. While Django URLconfs allow arbitrary regexes for powerful URL-matching capability, you’ll probably use only a few regex patterns in practice. Here’s a small selection of common patterns:
Symbol | Matches |
. (dot) | Any character |
\d | Any digit |
[A-Z] | Any character, A-Z (uppercase) |
[a-z] | Any character, a-z (lowercase) |
[A-Za-z] | Any character, a-z (case insensitive) |
+ | One or more of the previous expression (e.g., \d+ matches one or more digit) |
[^/]+ | All characters except forward slash |
? | Zero or more of the previous expression (e.g., \d* matches zero or more digits) |
{1,3} | Between one and three (inclusive) of the previous expression |
If we ignore the documentation comments at the top of the file, here’s the essence of a URLconf:
Let’s step through this code one line at a time:
- The first line imports two functions from the django.conf.urls module: include which allows you to include a full Python import path to another URLconf module, and url which uses a regular expression to pattern match the URL in your browser to a module in your Django project.
- The second line calls the function admin from the django.contrib module. This function is called by the include function to load the URLs for the Django admin site.
- The third line is urlpatterns – a simple list of url() instances.
The main thing to note here is the variable urlpatterns, which Django expects to find in your URLconf module. This variable defines the mapping between URLs and the code that handles those URLs. To add a URL and view to the URLconf, just add a mapping between a URL pattern and the view function. Here’s how to hook in our hello view:
We made two changes here:
- First, we imported the hello view from its module – mysite/views.py, which translates into mysite.views in Python import syntax. (This assumes mysite/views.py is on your Python path.)
- Next, we added the line url(r’^hello/$’, hello), to urlpatterns. This line is referred to as a URLpattern. The url() function tells Django how to handle the URL that you are configuring. The first argument is a pattern-matching string (a regular expression; more on this in a bit) and the second argument is the view function to use for that pattern. url() can take other optional arguments as well.
One more important detail we’ve introduced here is that ‘r‘ character in front of the regular expression string. This tells Python that the string is a “raw string” – its contents should not interpret backslashes. In normal Python strings, backslashes are used for escaping special characters – such as in the string “\n“, which is a one-character string containing a newline.
When you add the r to make it a raw string, Python does not apply its backslash escaping – so, “r’\n’” is a two-character string containing a literal backslash and a lowercase “n”. There’s a natural collision between Python’s usage of backslashes and the backslashes that are found in regular expressions, so it’s best practice to use raw strings any time you’re defining a regular expression in Django.
In a nutshell, we just told Django that any request to the URL /hello/ should be handled by the hello view function. It’s worth discussing the syntax of this URLpattern, as it may not be immediately obvious. Although we want to match the URL /hello/, the pattern looks a bit different than that. Here’s why:
- Django removes the slash from the front of every incoming URL before it checks the URLpatterns. This means that our URLpattern doesn’t include the leading slash in /hello/. At first, this may seem unintuitive, but this requirement simplifies things – such as the inclusion of URLconfs within other URLconfs.
- The pattern includes a caret (^) and a dollar sign ($). These are regular expression characters that have a special meaning: the caret means “require that the pattern matches the start of the string,” and the dollar sign means “require that the pattern matches the end of the string.”
This concept is best explained by example. If we had instead used the pattern ^hello/(without a dollar sign at the end), then any URL starting with /hello/ would match, such as /hello/foo and /hello/bar, not just /hello/.
Similarly, if we had left off the initial caret character (i.e., hello/$), Django would match any URL that ends with hello/, such as /foo/bar/hello/. If we had simply used hello/, without a caret or dollar sign, then any URL containing hello/ would match, such as /foo/hello/bar.Thus, we use both the caret and dollar sign to ensure that only the URL /hello/ matches – nothing more, nothing less.
Most of your URLpatterns will start with carets and end with dollar signs, but it’s nice to have the flexibility to perform more sophisticated matches. You may be wondering what happens if someone requests the URL /hello (that is, without a trailing slash). Because our URLpattern requires a trailing slash, that URL would not match. However, by default, any request to a URL that doesn’t match a URLpattern and doesn’t end with a slash will be redirected to the same URL with a trailing slash (This is regulated by the APPEND_SLASH Django setting, which is covered in Appendix D).
The other thing to note about this URLconf is that we’ve passed the hello view function as an object without calling the function. This is a key feature of Python (and other dynamic languages): functions are first-class objects, which means you can pass them around just like any other variables. Cool stuff, eh?
To test our changes to the URLconf, start the Django development server, by running the command python manage.py runserver from within your Python virtual environment. (If you left it running, that’s fine, too. The development server automatically detects changes to your Python code and reloads as necessary, so you don’t have to restart the server between changes.)
The server is running at the address http://127.0.0.1:8000/, so open up a web browser and go to http://127.0.0.1:8000/hello/. You should see the text “Hello world” – the output of your Django view, as below
Regular Expressions
Regular expressions (or regexes) are a compact way of specifying patterns in text. While Django URLconfs allow arbitrary regexes for powerful URL-matching capability, you’ll probably use only a few regex patterns in practice. Here’s a small selection of common patterns:
Symbol | Matches |
. (dot) | Any character |
\d | Any digit |
[A-Z] | Any character, A-Z (uppercase) |
[a-z] | Any character, a-z (lowercase) |
[A-Za-z] | Any character, a-z (case insensitive) |
+ | One or more of the previous expression (e.g., \d+ matches one or more digit) |
[^/]+ | All characters except forward slash |
? | Zero or more of the previous expression (e.g., \d* matches zero or more digits) |
{1,3} | Between one and three (inclusive) of the previous expression |