Django Routing Sample
Open-source sample provided by AppSeed to explain Django routing mechanism.
This sample might be useful to beginners to understand how the routing system works in Django Web Framework. In the end, the sample will route three things: a default route that shows a simple Hello World, a 2nd route that displays a random number at each page refresh, and the last route that shows a random image pulled from the internet.
Resources
Django Routing Sample - the source code (Github/MIT License)
More Django Samples provided with authentication, basic modules
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.
Read more about Django Framework - quick introduction
How to code this sample
This sample can be coded from scratch by following the steps below.
Check Python Version
Create/activate a virtual environment - Unix-based system
For Windows, the syntax is slightly different
Install Django
Create a new Django Project
Inside the new directory, we will invoke startproject
subcommand
Note: Take into account that .
at the end of the command.
Setup the database
Start the app
At this point we should see the default Django page in the browser:
Create a new Django app
Add a simple route
Let's edit sample/views.py
as shown below:
Configure Django to use the new route - update config/urls.py
as below:
In other words, the default route is served by hello
method defined in sample/views.py.
New Route - Dynamic content
Let's create a new route that shows a random number - sample/views.py
.
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:
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.
The controller code should be defined in sample/views.py
.
To see the effects in the browser, the routing should be updated accordingly.
The browser sample output returned by a local iteration:
Resources
Read more about Django (official docs)
Start fast a new project using development-ready Django Starters
Last updated