Getting Started with Python and Django

Django is a Web Application Framework that was originally released in July of 2005. Since then, it has evolved into a highly-scalable platform for serving up content on some of the highest-traffic websites on the internet, including: Instagram, Reddit and Disqus.

Reasons to use Django
  • Great Documentation
  • Python
  • Full Stack Framework
  • Works as a typical database-backed web application
What version of Python do I have?

If you don't have python, download it here and install it. Many systems already have Python installed. If you already have Python installed, use the following command to see what version you have:

$ python --version

Different versions of Django work with specific versions of Python. See the compatibility chart.

Additional Python Environment Setup

In order to manage our environment and dependencies, we need to:

$ python get-pip.py
  • In addition, we should also set up virtualenv so that we don't have to install a system-wide version of Django. This allows each development instance to be tailor-made for the version of software being worked on. See documentation for virtualenv to find out more.

Declare which directory will be used to store virtual environment settings using the following, and substituting ENV with the the name of the directory you want to create:

$ virtualenv ENV 

We can then begin using this virtual environment by activating it. The installation of Django in the following steps (and any additional packages we install later) will be stored in the ENV directory we created:

$ source ENV/bin/activate

At this point, your prompt will have a () at the front of it indicating that you are in virtual environment mode. If you named your folder something like venv, your prompt will have a (venv) in front of it.

Any time you want to exit the virtual environment, just type:

$ deactivate

For the rest of this tutorial, make sure your virtual environment is activated.

In addition to the virtualenv tool, take a look at the virtualenvwrapper tool for even more advanced management of virtual environments.

Install Django

First, make sure you have your virtualenv active. Install Django by running:

$ pip install django

We can then verify the version of Django installed by running the command:

$ python -c "import django; print(django.get_version())"

If this results in an error, revisit the steps above.

First Django Web Project

Now that we have the environment set up for Django, it's time to create our project.

Create new project

Go to the directory where you want to create the new project. Run the following command to create a new directory where the project will live, replacing whateverproject with your project's (and new directory) name:

$ django-admin startproject whateverproject

This creates the following skeleton application:

whateverproject/  
    manage.py
    whateverproject/
        __init__.py
        settings.py
        urls.py
        wsgi.py
  • manage.py - This is the command runner. You will never edit this. This is the command-line utility for interacting with the new project
  • __init__.py - An special empty file that let's python know that this directory is really a package and can be imported
  • settings.py - the settings and configuration of the new project
  • urls.py - the URL mapper that handles URL dispatching
  • wsgi.py - used as an entry point for a web server to serve this project. This is Web Server Gateway Interface (WSGI) compatible (Green Unicorn, CherryPy, uWSGI, mod_wsgi)
How to run the development web server

Change to the project directory where manage.py is located...

$ cd whateverproject

... and run the following command:

$ python manage.py runserver

You may see a few warnings, but we will address those later. Point the URL in a web browser to http://127.0.0.1:8000/ and you should see this page:

Press CONTROL-C on the keyboard to stop the web server.

Project vs Application

A Django project is is made up of one or more Applications. These applications can be developed and installed inside the Django project, and each one typically handles one type of activity, such as authentication, managing sessions, etc. We are going to create a basic application that handles a web request and returns data from a database.

How to create an application

First, make sure you are in the same directory as manage.py. We create a blank skeleton application by running the following command, passing a name in for our application. In this example, we're using the name whateverapp:

$ python manage.py startapp whateverapp

This creates the following in the file system:

whateverapp/  
    __init__.py
    admin.py
    models.py
    tests.py
    views.py
    migrations/
        __init__.py
Installing the application

In settings.py, we let the project know that we want to use the newly created application by adding it to the bottom of the INSTALL_APPS entry like this:

INSTALLED_APPS = (  
    'django.contrib.auth',
    'django.contrib.contenttypes',
    ...
    'whateverapp',
)
Handling URL routing

In the project's urls.py file, we write a regular expression (regex) that maps a url to a view. This tells Django to run the view code when a specific URL is called. So why do we use regex?

  • Regex is very fast
  • Regex is flexible
  • Regex is used in abundance across various programming languages

Edit urls.py to include:

urlpatterns = [  
    url(r'^$', 'whateverapp.views.index', name='index'),
]
  • url is the function call which builds the url patterns
  • r'^$' is the Python literal string representation for a regex
  • whateverapp.views.index is the Python import string to get the view
  • name='index' is the identifier we use for this url pattern
Views

A view is code that takes an HTTP Request object and returns an HTTP Response object.

In whateverapp/views.py add a HttpResponse handler to the index view by importing it into the file, then returning it:

from django.http import HttpResponse

def index(request):  
    return HttpResponse("Hello world!")

Make sure you are in the project's root directory where manage.py is located, then run the following command to start the server again:

$ python manage.py runserver

Point the URL in a web browser to http://127.0.0.1:8000/ and you should see the following on the page:

Hello world!  

Press CONTROL-C on the keyboard to stop the web server.

Congratulations!

We've created a working application using Python and Django. In Part 2, we will dive into topics such as using Templates, accessing the database using Models and more.

Next: Getting Started with Python and Django - Part 2

Source Code on GitHub: https://github.com/justinbellamy/whateverprojectPython