Open-source sample provided by AppSeed to explain Django Routing mechanism. All commands used to code the project and also the relevant updates are listed below. For newcomers, 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.
For support and more Django Samples join AppSeed.
Chech Python Version
$ python --version
Python 3.8.4 <-- All good
Create/activate a virtual environment
$ # Virtualenv modules installation (Unix based systems)
$ virtualenv env
$ source env/bin/activate
$
$ # Virtualenv modules installation (Windows based systems)
$ # virtualenv env
$ # .\env\Scripts\activate
Install Django
$ pip install django
Create Django Project
$ mkdir django-sample-urls
$ cd django-sample-urls
Inside the new directory, we will invoke startproject
subcommand
django-admin startproject config .
Note: Take into account that
.
at the end of the command.
Setup database
$ python manage.py makemigrations
$ python manage.py migrate
Start the app
$ python manage.py runserver
Create sample app
$ python manage.py startapp sample
Add a simple route - sample/views.py
def hello(request):
return HttpResponse("Hello Django")
The browser output
Configure Django to use the new route
Edit 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
]
In other words, the default route is served by hello
method defined in sample/views.py
Add 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() ) )
The new method invoke random()
from Python core library, convert the result to a string and return the result.
The browser output
Display a random image
The controller code can be found 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")
To see the effects in the browser, the routing should be updated acordingly.
# 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),
]
The browser output
For support and more Django Samples join AppSeed.
Django Routing - Open-source Sample provided by AppSeed.