Django for ISchoolers

Revision as of 08:16, 17 November 2011 by imported>Aldeka (→‎Using version control)

This is a tutorial for how to build a question-and-answer type site using Django and various other technologies, plus some lessons in general web dev concepts and best practices along the way.

The basics

Prerequisites

Assumptions

This tutorial assumes you know how to access the command line/terminal on your computer and how to move around (cd) and view files (ls) in it. It also assumes you're reasonably familiar with Python, the Best Programming Language Ever. (Okay, editorializing slightly.)

This tutorial also tends to be oriented towards people with some familiarity with HTML, CSS, and JS (since most of you guys are IOLabbers).

Stuff to install

TODO: Actually write my own dang installation instructions.

Prior to starting this tutorial, please install Python, git, pip, virtualenv, Django, and South on your computer. There's instructions for all of those at http://pystar.org/setup_machine.html.

Setting up yer env

Once you've got pip and virtualenv installed, in your terminal, go into the folder you want to keep this tutorial code in and type (one line at a time):

$ virtualenv --no-site-packages django-tutorial-env

$ source django-tutorial-env/bin/activate

(django-tutorial-env)$ pip install django

(django-tutorial-env)$ pip install south

This will make and activate a virtual python environment for just this tutorial app. While this is a bit overkill if you only have one Django app at a time on your system, giving each Python app you work on its own environment is a good best practices just in case e.g. you're working on multiple apps, which use different versions of Django or other libraries, and you don't want them to conflict with each other.

To turn off the virtualenv (you can see it's active because the env name will appear in parentheses before your terminal prompt), type 'deactivate'. To reactivate the env, type the line that begins with 'source' again.

Spec'ing yer application

Your client, LulzTech, wants you to build them a Q & A website. (For mysterious reasons, they don't want to use any of the open source Q&A website packages that are out there already; they want you to build one from scratch. Go figure.)

There are whole classes on how to research and decide what to build, and how to state those requirements in a useful, clear way. (Bob's ISSD class, for one.) So we won't go into that. For our initial prototype for our client, then, our requirements are as follows:

  • On the website, users can see the questions that have been asked and when they were posted
  • Under each question, users can read the answers that have been given so far (if any) and when they were posted
  • Users can submit a new question
  • Users can submit a new answer to a question
  • Users can edit an answer to a question
  • Users can delete an answer to a question

Meeting these requirements will take us until the 'Bonus points' section. Once we get there, we can add more requirements.

Our prototype will have three pages: an index page of questions (and a form to ask a new question), a question page with the question and its answers (with a form to add a new answer), and a page to edit an answer to a question.

To support these pages, we will need two abstractions (objects, or models): Questions, and Answers.

Starting yer project

Activate your environment in your terminal

If you haven't already, run $ source django-tutorial-env/bin/activate in your terminal window.

Set up your git repository

If you're following this tutorial in class, in your terminal, run $ git clone git://github.com/aldeka/django-for-ischoolers.git. This won't download hardly anything interesting, but it will make it easy for you to sync up with the class later.

We'll be using the master branch (the default name for the main branch of code, which you're in right now) for syncing up throughout the class in case you get lost. You'll need to make your own branches for playing with the code on your computer, so that it doesn't interfere w. re-syncing later.

Think of branches in git as alternate timelines--you "branch" off of the main timeline of changes to the code into a separate timeline. You can try out a new feature or code setup in a branch, without overwriting or getting in the way of yourself or anybody else working on the code as-is. Sometimes a new idea doesn't work out, and you delete the branch or just let it sit around. Sometimes the new feature works, though, and if so you can merge it into the "real" timeline. You can make as many branches as you want, and branches of branches. You can even share branches with others (though we won't be doing that today). Git's branching system (and its non-centralized architecture generally) make it easy to try out new ideas in code without having to ask permission of everyone else on the project first.

To make your first branch, type $ git branch my-chunk-1 to make your new branch, and $ git checkout my-chunk-1 to switch into that branch. Type $ git branch to confirm that you're in your new branch (and that you only have two branches so far).

If you're not following this tutorial in class, just run $ git init.

Create your Django project

Let's create your first Django project, called "mysite".

$ django-admin.py startproject mysite

You'll see we made a folder called "mysite", with some files in it. Let's check them out!

$ cd mysite
$ ls
__init__.py
manage.py
settings.py
urls.py

These files are:

  • __init__.py: An empty file that tells Python that this directory should be considered a Python module. Because of the __init__.py file, you can use import to import myproject.
  • manage.py: A command-line utility that lets you interact with this Django project in various ways. You can read all the details about manage.py in django-admin.py and manage.py.
  • settings.py: Settings/configuration for this Django project.
  • urls.py: The URL declarations for this Django project; a “table of contents” of your Django-powered site.

Start your local development server

  • Django, handily, comes with some local server software (warning: never use Django's built-in dev server for actually hosting a site in production! It's not meant for that.). This local dev server makes it easy to see the changes you make to your web app as you build it. Let's make sure our project works by verifying that the dev server will start.
    • Run the command:

python manage.py runserver

    • Review the output in your terminal. It should look similar to:

Validating models...
0 errors found.

Django version 1.2, using settings 'myproject.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

  • Now that the server’s running, visit http://127.0.0.1:8000/ with your Web browser. You’ll see a “Welcome to Django” page, in pleasant, light-blue pastel. It worked!
  • Observe the logging that happens in the terminal where your server is running:

[24/Mar/2011 11:50:18] "GET / HTTP/1.1" 200 2057

which has the format:

DATE METHOD URL PROTOCOL RESPONSE_CODE CONTENTSIZE

  • Exit the server by returning to the terminal instance where the development server is running and pressing CONTROL-C on your keyboard.

Using version control

Before we do anything else, let’s commit our work. We'll be doing this with a piece of version control software called git.

What's this version control nonsense? Well, you probably know the value of saving your work. When writing an important term paper, you want to "Save early, save often" to make sure you don't lose your work if your computer crashes or something else bad happens! But most paper-writing software isn't very good at saving your history--if you decide to delete a section of your paper, save it, and then later decide that you want that section back, most document writing software doesn't have any way of helping you do that. There's only one saved version of the paper (unless you save multiple copies over time, yourself, by hand).

Programmers often have to go back into the history of a program to change things--whether it's to diagnose a bug or redesign how a feature works. Programmers also have to have an easy way of being able to edit the same application at the same time, and to share their edits with each other. Thus, besides saving their work the normal way, programmers commit their code using version control software.

Each commit is a checkpoint in time, containing the diff--the "difference", all of the changes you made to your code base -- between that commit and the commit before it. Different branches in git share the commits made prior to the branching-off point, then each have their own commit history.

  • To make a commit, first type git status into your terminal. This will let you know what changes git has noticed in your code and which of those changes, if any, are staged and ready to be committed.

$ git status

  1. On branch my-chunk-1
  2. Initial commit
  3. Untracked files:
  4. (use "git add <file>..." to include in what will be committed)
  5. __init__.py
  6. manage.py
  7. settings.py
  8. urls.py

nothing added to commit but untracked files present (use "git add" to track)

"Untracked files" means that git has noticed some new files inside its folder, but you haven't told git explicitly that you want it to "listen" for, and track, changes in those files.

  • Add one file: git add manage.py. What does git status say now?
  • Add all the files to the repo, in the local directory:

$ git add *.py # all .py files, using a wildcard match.

What does git status say now?

  • git commit to commit those files:

# -m -> what is the 'message' for the commit
git commit -m "Initial commit of Django project from the IOLab Django workshop"

  • Look at your changes with git log to see your history. Is your commit message there?

Huzzah! We committed our changes so far. Now let's make some more changes!

Set up settings

(skipping demonstration of magic git backup powers)

Projects v. apps -- what's the difference?

Starting yer app

Test-driven development, part one

(use provided tests.py file)

  1. Think
  2. Test
  3. Code
  4. Commit

M-V-C separation

urls.py

views.py

Databases and the ORM (or: finally something that HTML/CSS/JS couldn't do for you on its own)

models.py

Database migrations and South, part one

Let's add some data (via the Django shell)!

Database migrations and South, part two

Let's auto-populate some data (using a script in the shell)!

Views with actual data

Django templates 101

Hooking up views to our templates

Oh, CRUD! (plus, ModelForms)

Bonus points

Static files (aka: Django for designers)

AJAX and Django

Test-driven development, part two

(walk through how to write tests for a new feature)

Authentication and Users (and reusing apps)

Deploying to a real live server