4.2. Add a Route#

To a web application a route is a URL pattern that is handled by a particular view. In Django a view is a function that generates the HTML to be sent back to the web browser. If you carefully followed the Django instructions you probably noticed that going to the index page (/) of your web application takes you to a 404 error page. That’s because you removed the default route that matches URLs that aren’t polls/ or admin/. In this lab you’ll create a new view that shows a useful index page.

Installing a New Python Package#

I’ve created a function that gathers information about the machine your app is running on and displays the information. The function uses the psutil package which isn’t installed by default. Install it into your dev environment like this:

$ pip install psutil


Make a note of every Python package you install, you’ll need it in your Dockerfile

Create an HTML Template#

It’s awkward to put a lot of HTML code into Python files. Django comes with a templating engine that allows you to write mostly HTML code that has values inserted into it by Django. Put this code into a file called polls/templates/index.html. You will have to create the polls/templates directory first.

<!DOCTYPE html>
<title>My CIS-92 Project</title>
<h1>{{ host }}</h1>
<strong>A project by {{ user }}</strong>
<p><a href="polls/">Goto Polls</a></p>
<p><a href="admin/">Goto Admin</a></p>
<h2>Network Interfaces:</h2>
<pre>{% for iface, data in net_if_addrs.items %}
{{ iface }}
  {% for addrfam in data %}{{ addrfam.address }}
  {% endfor %} 
{% endfor %}</pre>
<h2>CPU Load Average:</h2>
<pre>{{ loadavg }}</pre>
<h2>Disk Usage</h2>
<pre>Total: {{ disk_usage.total | floatformat:"0g" }} Used: {{ disk_usage.used | floatformat:"0g" }} {{ disk_usage.percent }}%</pre>

Create a Function#

This Python function is what gets called when your route is activated. A function can serve any URL route, even more than one in your application. Functions can take arguments from the route too. Take a look at how the polls route works for more information. Add this function to polls/views.py:

import os 
import psutil 
from django.shortcuts import render 

def site_index(request):
    """The default view for our page."""
    template_data = {
        'user': os.environ.get('STUDENT_NAME', "(No Username)"),
        'host': os.environ.get('SITE_NAME', "localhost.localdomain"),
        'net_if_addrs': psutil.net_if_addrs(),
        'disk_usage': psutil.disk_usage('/'),
        'loadavg': psutil.getloadavg(),
    return render(request, "index.html", template_data)


This function uses environment variables! We’ll talk about those in the next lab.

Add the Route#

Now that we have a template and a function we need to tell Django to call your function when it sees a certain URL pattern. In our case we just want to show a working page in response to an empty URL pattern. There are two changes we need to make to mysite/urls.py. Make it look like this:

from django.contrib import admin
from django.urls import include, path
from polls.views import site_index

urlpatterns = [
    path("polls/", include("polls.urls")),
    path("admin/", admin.site.urls),
    path("", site_index), # Default 

Test Your Changes#

Now that you’ve updated the source you should be able to run your development server and see the new landing page.

$ python manage.py runserver 

You will notice that the page says “A project by (No Username)”. Your name is controllable by the environment. Try restarting your development server after setting the STUDENT_NAME and SITE_NAME variables in the shell:

$ export STUDENT_NAME="Bike Batera"
$ export SITE_NAME="www.bikebatera.com"
$ python manage.py runserver