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.
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.
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:
Django - Default Project Page.
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:
Django Routing - Dynamic Content Route.
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:
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
]
...
from random import random
...
def myrandom(request):
return HttpResponse("Random - " + str( random() ) )