How URL Routing in Django Works

A URL is a uniform resource locator. It contains the address that links to a resource such as an HTML page.

For example, “https://henrydangprg.com” is a URL, that links to the HTML page that contains this website. A single website, like this, can have many other URL’s formed by adding a backslash (“/”) after the domain name.

If you wanted to access the about page on this website, you would add “/about/” to the end of the home page’s URL. It can be visualized like a tree.

You start with the base website, and you have other possible URL’s accessible by adding a backslash and some word.

  • https://henrydangprg.com/
    • about/
    • contact/
    • infinitely-many-other-possibilities/
      • which-can-contain-other-links/
        • containing-potentially-even-more-links/

In theory, you can have something like :

https://henrydangprg.com/foo/bar/foobar/foobarbar/foofoo-ad-infinitum/

How Does It Work in Django?

In Django, the premise is exactly the same. Inside each project is a urls.py file.

You’ll see something along the lines of this :

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

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

Here, you can see that Django handles the URL routing with regular expressions. The ‘r’ before a string indicates that the following string is raw input. This means that Python will not convert things like ‘\n’ into a new line, and will instead process it as is.

You can play around with the urlpatterns list, and add new url’s to test that it works.

For example, if we change it to :

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

Then foobar will become a possible extension to your website’s URL. Assuming you’re using localhost and a port of 8000, it would be 127.0.0.1:8000/foobar/ to access your new URL.

If you want to go down two layers deep, like 127.0.0.1:8000/foobar/foo, you should create a new app.

Let’s make a new app called “foobar”.

django-admin startapp foobar

Modify the urlpatterns list inside your project’s urls.py file. We are now going to add foobar’s urls.py file into the project’s urls.py.

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

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

Essentially, any time we visit 127.0.0.1:8000/foobar/, Django will see that we want to access “foobar”, and will check foobar’s urls.py for the next portion of the URL.

Now, we have to add add URLs into foobar. Go into the foobar directory and modify urls.py.

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

from . import views

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

I don’t suggest you actually make every URL link to admin.site.urls, but for the sake of simplicity, we will stick to using that.

The ‘^$’ simply indicates that if there is nothing, then load the admin page. In this case, it would be 127.0.0.1:8000/foobar/ because there is nothing after “foobar/”, which is what our project’s urls.py looked up until.

We also added “foo” to our urlpatterns, which means we can now visit 127.0.0.1:8000/foobar/foo, allowing us to add extensions to our URL.

You can add virtually any URL you want, and as many levels of URLS as needed. You don’t even have to add new apps for each new extension. However, you will have to write a lot of duplicated code if you do that.


#With new apps 

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

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

#Without new apps, anti-DRY

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

You can see that you would have to write out the full URL each time. If you had 100 URL’s, all 100 would have to be crammed into this single urlpatterns list, and if it goes 10 layers deep, you would have to write it all out each time.

Conclusion

URL routing with Django is absurdly easy, provided that you know a little bit of regex. However, if you are struggling with regular expressions, you can click here for an interactive regular expressions tester.
Best of luck with learning Django, and happy coding!

 

Null Island – The Most Famous Island that Doesn’t Exist

It’s been a long and tiresome week of work, and you want a vacation.

You search online for some decent vacation spots.

Hawaii? Nah. Canada? Already been there.

But hold on, something catches your eye. Null Island? Thousands of visitors? And look at that population density! All those posts from (0,0)?

And so you set out on an arduous and dangerous journey to Null Island, only to find this.

Null-island-buoy
Photo from Wikipedia

Yep. Null Island, the most popular tiny island you’ve found in your life, doesn’t exist.

What’s Going on Here?

Null Island, located with the geographic coordinates (0,0), is a byproduct formed by bad programming.

How did it happen?

Some developers who were creating a GPS system decided that, if a person’s coordinates couldn’t be found, that instead of setting them (Null, Null), they were instead set to (0,0).

In psuedocode, it went down something like this :

if user's x coordinate is Null
  set user's x coordinate to 0

if user's y coordinate is Null
  set user's y coordinate to 0

Not only is this kind of code an anti-pattern, but for something such as position tracking, this can have serious consequences.

For example, in Wisconsin, many voters were in locations that did not have registered coordinates. However, in order to vote, they needed to use a new geocoding system that tied their house address to a geographical coordinate.

Unfortunately, the Wisconsin voters were given a geographical coordinate of (0,0), or Null Island. For a population of nearly 6 million, the problem was quickly discovered and fixed, but it is yet another example of how bad programming can wreck havoc.

To prevent mistakes like these, ask yourself if what you’re doing makes sense in a different context.

Here are some similar scenarios, using the same logic that caused the Null Island issue.

if user's phone number is Null
  set user's phone number to 000-000-0000

if user's pin number is Null
  set user's pin number to 0000

if user's credit card number is Null
  set user's credit card number to
    0000 0000 0000 0000

In scenarios where the 0 is significant, you cannot replace null with zero. If your wallet is null, it means you don’t have any money. Your balance is 0. If your friend count is null, it means you have no friends, so your friend count is 0.

However, if the zero matters, such as in a phone number, you can’t set the user’s phone number to 000-000-0000. Similarly, if you have an expensive watch, and the price is null because it’s not for sale, that doesn’t mean your watch costs $0.00. That would imply that you’re giving it away for free.

Conclusion

Null Island is a silly coding mistake that carries significant consequences, even today.

That’s not to say that every single mistake you make will effect an entire state’s voter population, but it can happen.

If you want to avoid creating the next equivalent of Null Island, leave your user’s input as is instead of attempting to change it. Null means null. Leave it as null.