Django Routing - A practical introduction
Tags: webdev, python, django
Published: 2021-06-15 16:18:48

---
title: Django Routing - A practical introduction
published: true
description: A soft introduction to Django Routing System
tags: webdev, python, django
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ibeokmvowrkwu9dmxhk.png
canonical_url: https://docs.appseed.us/samples/django/django-routing
---
Hello Coders,

This article is a soft and practical introduction to [Django Routing](https://docs.appseed.us/samples/django/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!* 

---

- [Django Routing Sample](https://github.com/app-generator/django-routing-sample) - the source code (Github/MIT License)
- More [Django Samples](https://appseed.us/admin-dashboards/django) provided with authentication, basic modules

---

## [What is Django](https://docs.appseed.us/content/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](https://www.djangoproject.com/) - official website
- [Django Docs](https://docs.djangoproject.com/en/3.0/) - recommended starting point for every aspire Django developer 

--- 

## Let's Code Django

> Check Python Version - recommended version is Python3

```bash
$ python --version
Python 3.8.4        <-- All good, we have a 3.x version
```

>  Create/activate a virtual environment - Unix-based system

```bash
$ virtualenv env
$ source env/bin/activate  
```
For Windows, the syntax is slightly different

```bash
$ virtualenv env
$ .\env\Scripts\activate
```

> Install Django

```bash
$ pip install django
```

>  Create a new Django Project

```bash
$ mkdir my-django-sample
$ cd my-django-sample
```

Inside the new directory, we will invoke `startproject` subcommand:

```bash
$ django-admin startproject config .
```

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

> Setup the database

```bash
$ python manage.py makemigrations
$ python manage.py migrate
```

> Start the app

```bash
$ python manage.py runserver 
$
$ # Access the web app in browser: http://127.0.0.1:8000/
```

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

![Django - Default Project Page.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pklhkp0fjhm5blmnabv4.png)
 
> Create a new Django application

```bash
$ python manage.py startapp sample
```

---

## Add a simple Django Route

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

```python
def hello(request): 
    return HttpResponse("Hello Django") 
```

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

```python
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
]
```

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.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bwb5l9imd65ozlq1um4m.png)
 
---

## New Route - Dynamic content

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

```python
...
from random import random
...
def myrandom(request): 
    return HttpResponse("Random - " + str( random() ) ) 
```

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.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vjmpago4a1dvfmh381ep.png)

---

## 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. 

```bash
$ pip install requests
```

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

```python
...
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")
``` 

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

```python
# 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), 
]
```
 
Here is a sample output - randomly selected from a public service:

![Django Routing - Random number returned to the user.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y1csguhqqjfrbr442jbj.png)

---

> Thanks for reading! For more resources, feel free to access: 

- 👉 More [Django Dashboards](https://appseed.us/admin-dashboards/django/) - a curated index 
- 👉 [Django App Generator](https://app-generator.dev/django/) - A 2nd generation App Builder