Django URLs

Part of this chapter is based on tutorials by Django Girls Tutorial : https://tutorial.djangogirls.org

Let's learn a little bit about Django URLs.

What is a URL?

A URL is simply a web address. You can see a URL every time you visit a website – it is visible in your browser's address bar. (Yes!127.0.0.1:8000is a URL! Andhttps://djangogirls.orgis also a URL.)

Every page on the Internet needs its own URL. This way your application knows what it should show to a user who opens that URL. In Django we use something called URLconf(URL configuration).

URLconf is a set of patterns that Django will try to match with the requested URL to find the correct view.

How do URLs work in Django?

Let's open up thetbgsite/urls.pyfile in your code editor of choice and see what it looks like:

"""mysite URL Configuration

[...]
"""
from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
]

As you can see, Django has already put something here for us.

Lines between triple quotes ('''or""") are called docstrings – you can write them at the top of a file, class or method to describe what it does. They won't be run by Python.

The admin URL, which you visited in previous chapter, is already here:

url(r'^admin/', admin.site.urls),

This line means that for every URL that starts with admin/, Django will find a corresponding view. In this case we're including a lot of admin URLs so it isn't all packed into this small file – it's more readable and cleaner.

Regex

Do you wonder how Django matches URLs to views? Well, this part is tricky. Django usesregex, short for "regular expressions". Regex has a lot (a lot!) of rules that form a search pattern. Since regexes are an advanced topic, we will not go in detail over how they work.

If you still wish to understand how we created the patterns, here is an example of the process – we will only need a limited subset of the rules to express the pattern we are looking for, namely:

  • ^ for the beginning of the text
  • $ for the end of the text
  • \d for a digit
  • + to indicate that the previous item should be repeated at least once
  • () to capture part of the pattern

Anything else in the URL definition will be taken literally.

Now imagine you have a website with the address likehttp://www.mysite.com/post/12345/, where12345is the number of your post.

Writing separate views for all the post numbers would be really annoying. With regular expressions, we can create a pattern that will match the URL and extract the number for us:^post/(\d+)/$. Let's break this down piece by piece to see what we are doing here:

  • ^post/
    Tells Django to take anything that has post/ at the beginning of the url (right after ^)

  • (\d+)
    Means that there will be a number (one or more digits) and that we want the number captured and extracted

  • /
    Tells django that another / character should follow

  • $
    Indicates the end of the URL meaning that only strings ending with the / will match this pattern

Your first Django URL!

Time to create our first URL! We want 'http://127.0.0.1:8000/' to be the starting page for our game.

We also want to keep thetbgsite/urls.pyfile clean, so we will import URLs from our myfirstgame application to the maintbgsite/urls.pyfile.

Go ahead, add a line that will importmyfirstgame.urls. Note that we are using theincludefunction here so you will need to add that import.

Yourtbgsite/urls.pyfile should now look like this:

from django.conf.urls import include
from django.conf.urls import url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'', include('myfirstgame.urls')),
]

Django will now redirect everything that comes into 'http://127.0.0.1:8000/' totbgsite.urlsand look for further instructions there.

Writing regular expressions in Python is always done withrin front of the string. This is a helpful hint for Python that the string may contain special characters that are not meant for Python itself, but for the regular expression instead.

myfirstgame.urls

Create a new empty file named urls.py in the blog directory. All right!

Add these first two lines:

from django.conf.urls import url
from . import views

Here we're importing Django's functionurland all of ourviewsfrom themyfirstgameapplication. (We don't have any yet, but we will get to that in a minute!)

After that, we can add our first URL pattern in myfirstgame/urls.py:

urlpatterns = [
    url(r'^$', views.index, name='index'),
]

As you can see, we're now assigning aviewcalled index to the^$URL. This regular expression will match^(a beginning) followed by$(an end) – so only an empty string will match. That's correct, because in Django URL resolvers, 'http://127.0.0.1:8000/' is not a part of the URL. This pattern will tell Django thatviews.indexis the right place to go if someone enters your website at the 'http://127.0.0.1:8000/' address.

The last part,name='index', is the name of the URL that will be used to identify the view. This can be the same as the name of the view but it can also be something completely different. We will be using the named URLs later in the project, so it is important to name each URL in the app. We should also try to keep the names of URLs unique and easy to remember.

If you try to visit http://127.0.0.1:8000/ now, then you'll find some sort of 'web page not available' message. This is because the server (remember typingrunserver?) is no longer running.

Take a look at your server console window to find out why.Your console is showing an error, but don't worry – it's actually pretty useful: It's telling you that there is no attribute 'index'. That's the name of the _view _that Django is trying to find and use, but we haven't created it yet.

At this stage your /admin/will also not work. No worries – we will get there.

If you want to know more about Django URLconfs, look at the official documentation:

https://docs.djangoproject.com/en/2.0/topics/http/urls/

We are very nearly there, on to the next stop, let's create a view!

results matching ""

    No results matching ""