0 to 60 with Django in 5 steps

Django is great, but its tutorial is not: instead of focusing on a website that can control a Python application (which is what most of us care about), it discusses templates for admin pages and presenting 404 errors.  So let’s walk through making a Django app that can call a Python function, by doing the minimal amount of work (and reading) necessary.

Goal

Create a Django app that allows a user to run the following code via a web page:

import hashlib
def hash_this_number(number):
    return hashlib.sha1(number).hexdigest()

Obviously, the web page should be able to somehow take an argument for the number to hash, and should display the hashed value.

Step 0: Install Django

pip install django==1.8.6

Step 1: Create a project

django-admin startproject webhash
cd webhash

Step 2: Create an app

python manage.py startapp hasher

Step 3: Hook up the app

In webhash/settings.py, add hasher to the list of installed apps:

INSTALLED_APPS = (
 'django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'hasher'   # Add this line
)

In webhash/urls.py, add hasher to the list of acceptable URLs:

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^hasher/', include('hasher.urls'))  # Add this line
]

Create hasher/urls.py and add the following content:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^(?P<number_to_hash>.+)/$', views.index, name='index'),
]

Step 4: Create your view

Change the content of hasher/views.py to the following:

from django.http import HttpResponse
import hashlib

def hash_this_number(number):
    return hashlib.sha1(number).hexdigest()

def index(request, number_to_hash):
    hashed_value = hash_this_number(number_to_hash)
    return HttpResponse("The hash value of %s is %s." % (number_to_hash, hashed_value))

Step 5: Run your site!

python manage.py runserver

You should be able to go to localhost:8000/hasher/20 and see a response:

The hash value of 20 is 91032ad7bbcb6cf72875e8e8207dcfba80173f7c.

Nice job!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s