DEV Community

loading...
Cover image for Django Routing - A practical introduction

Django Routing - A practical introduction

Sm0ke
#Automation, my favorite programming language
Originally published at docs.appseed.us ・3 min read

Hello Coders,

This article is a soft and practical introduction to Django Routing System. The sample we will code during this tutorial, in the end, will implement three routes: a default route that shows a classic Hello World, a 2nd route that displays a random number at each page refresh, and the last route will show a random image pulled from the internet.

Thanks for reading! - Content provided by App Generator.



What is Django

Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experienced developers, it takes care of much of the hassle of Web development, so you can focus on writing your app without needing to reinvent the wheel. It’s free and open source.

  • Django - official website
  • Django Docs - recommended starting point for every aspire Django developer

Let's Code Django

Check Python Version - recommended version is Python3

$ python --version
Python 3.8.4        <-- All good, we have a 3.x version
Enter fullscreen mode Exit fullscreen mode

Create/activate a virtual environment - Unix-based system

$ virtualenv env
$ source env/bin/activate  
Enter fullscreen mode Exit fullscreen mode

For Windows, the syntax is slightly different

$ virtualenv env
$ .\env\Scripts\activate
Enter fullscreen mode Exit fullscreen mode

Install Django

$ pip install django
Enter fullscreen mode Exit fullscreen mode

Create a new Django Project

$ mkdir my-django-sample
$ cd my-django-sample
Enter fullscreen mode Exit fullscreen mode

Inside the new directory, we will invoke startproject subcommand:

$ django-admin startproject config .
Enter fullscreen mode Exit fullscreen mode

Note: Take into account that . at the end of the command.

Setup the database

$ python manage.py makemigrations
$ python manage.py migrate
Enter fullscreen mode Exit fullscreen mode

Start the app

$ python manage.py runserver 
$
$ # Access the web app in browser: http://127.0.0.1:8000/
Enter fullscreen mode Exit fullscreen mode

At this point we should see the default Django page in the browser:

Django - Default Project Page.

Create a new Django application

$ python manage.py startapp sample
Enter fullscreen mode Exit fullscreen mode

Add a simple Django Route

Let's edit sample/views.py as shown below:

def hello(request): 
    return HttpResponse("Hello Django") 
Enter fullscreen mode Exit fullscreen mode

Configure Django to use the new route - update config/urls.py as below:

from django.contrib import admin
from django.urls  import path
from django.conf.urls import include, url   # <-- NEW
from sample.views import hello              # <-- NEW

urlpatterns = [
    path('admin/', admin.site.urls),
    url('', hello),                         # <-- NEW
]
Enter fullscreen mode Exit fullscreen mode

In other words, the default route is served by hello method defined in sample/views.py. On access the root page, we should see a simple Hello Word message:

Django Routing - Simple Message returned to the user.


New Route - Dynamic content

Let's create a new route that shows a random number - sample/views.py.

...
from random import random
...
def myrandom(request): 
    return HttpResponse("Random - " + str( random() ) ) 
Enter fullscreen mode Exit fullscreen mode

The new method invoke random() from Python core library, converts the result to a string and returns the result. The browser output should be similar to this:

Django Routing - Random number returned to the user.


New Route - Random Images

This route will pull a random image from a public (and free) service and inject the returned content into the browser response. To achieve this goal, we need a new Python library called requests to pull the random image with ease.

$ pip install requests
Enter fullscreen mode Exit fullscreen mode

The code for the new route should be defined in sample/views.py.

...
import requests
...
def randomimage(request):
    r = requests.get('http://thecatapi.com/api/images/get?format=src&type=png')
    return HttpResponse( r.content, content_type="image/png")
Enter fullscreen mode Exit fullscreen mode

To see the effects in the browser, the routing configuration should be updated accordingly.

# Contents of config/urls.py
...
from sample.views import hello, myrandom, randomimage # <-- Updated 
...
urlpatterns = [
    path('admin/'     , admin.site.urls),
    url('randomimage' , randomimage),                 # <-- New
    url('random'      , myrandom),
    url(''            , hello), 
]
Enter fullscreen mode Exit fullscreen mode

Here is a sample output - randomly selected from a public service:

Django Routing - Random number returned to the user.


Thanks for reading! Feel free to AMA in the comments section.


More Django Resources

  • Read more about Django (official docs)
  • Start fast a new project using development-ready Django Starters

Discussion (8)

Collapse
uithemes profile image
ui-themes • Edited

Nice and simple.
Keep writing!

Collapse
sm0ke profile image
Sm0ke Author

Ty! More (simple) tutorials will come.
🚀🚀

Collapse
bensonmat8 profile image
bensonmat8

Loved the simple article!
Can someone tell me why '.' was added at the end of startproject command? Django documentation did not have that so was wondering what that does. I am kinda new django and was trying to learn as much as I can.

Collapse
sm0ke profile image
Sm0ke Author

Thank you! The . means to create the product in the current directory.
If you use the option to provide a directory name my_project for instance, Django will generate something like this:

  • my_project\my_project\settings...

In my projects i prefer to isolate the initial Django project in something names core or config.

Anyway, feel free to code the project in your own way.
🚀🚀

Collapse
crearesite profile image
WebsiteMarket

You should rename this tutorial to How to display a random cat with Django.
P.S. Really nice content!

Collapse
sm0ke profile image
Sm0ke Author

:) .. Thanks for your suggestion.
For the next article I will listen your advice and choose a funny title.

Collapse
cheatsheetmaker profile image
cheatsheetmaker

Thank for writing!

Collapse
sm0ke profile image
Sm0ke Author

Yw! More will come.
Feel free to suggest a Django-related topic.