{ "metadata": { "name": "django_tut" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "##Django Interactive Tutorial | by Andrew Conti\n", "\n", "An interactive tutorial that guides you through creating your first Django project. This notebook goes along with Chander Ganesan's Introduction to Django from Pycon 2012. \n", "\n", "\n", "**Additional materials for the tutorial include:**\n", "\n", "* [Overview](https://us.pycon.org/2012/schedule/presentation/327/) of the presentation. \n", "* [Video recording](http://youtu.be/hp5ymCrD9yw) of the presentation.\n", "* Chander Ganesan's [Slides](http://www.otg-nc.com/site_media/pdf/django2012.pdf)\n", "\n", "*Please click play on the video below and follow along with the slides. You cannot see what Ganesan is doing in the video so only the audio is useful. It\u2019s helpful to have his dialogue as you move through his tutorial.*\n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from IPython.display import YouTubeVideo\n", "YouTubeVideo('hp5ymCrD9yw')" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "\n", " \n", " " ], "metadata": {}, "output_type": "pyout", "prompt_number": 1, "text": [ "" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "First make sure you have Django Installed or install it using `pip install Django`. Test the installation with the code below:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import django\n", "print django.VERSION" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "(1, 5, 1, 'final', 0)\n" ] } ], "prompt_number": 2 }, { "cell_type": "code", "collapsed": false, "input": [ "# uncomment the line below when running for the first time. \n", "#!django-admin.py startproject tutorial" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "cd tutorial" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "C:\\Users\\Andrew\\Documents\\Kaggle\\tutorial\\django_tut\\tutorial\n" ] } ], "prompt_number": 43 }, { "cell_type": "code", "collapsed": false, "input": [ "ls" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ " Volume in drive C is OS\n", " Volume Serial Number is EA4A-2994\n", "\n", " Directory of C:\\Users\\Andrew\\Documents\\Kaggle\\tutorial\\django_tut\\tutorial\n", "\n", "06/19/2013 03:39 PM .\n", "06/19/2013 03:39 PM ..\n", "06/11/2013 03:53 PM hello_world\n", "06/10/2013 04:18 PM 251 manage.py\n", "06/19/2013 03:02 PM 5,579 settings.py\n", "06/19/2013 03:33 PM 11 test.py\n", "06/19/2013 03:24 PM 930 urls.py\n", "06/19/2013 03:32 PM 567 views.py\n", " 5 File(s) 7,338 bytes\n", " 3 Dir(s) 770,251,964,416 bytes free\n" ] } ], "prompt_number": 44 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###The files inside are:\n", "\n", "**'__init__.py'** : A file that causes Python to treat the directory as a package.\n", "\n", "**manage.py:** A command line utility to communicate with Django.\n", "\n", "**settings.py:** Configuration settings for the project.\n", "\n", "**urls.py:** URL declarations for the project. The URL's tell Django what to do when certain URL's \n", "are put into the browser\n", "\n", "The command line experssion:\n", "\n", " manage.py runserver\n", "\n", "starts a server that runs on local host [http://127.0.0.1:8000/](http://127.0.0.1:8000/) for development. To keep our notebook interactive, lets run our development server as a subprocess, so it can run in the background as we continue to develop our site. After clicking this link, [http://127.0.0.1:8000/](http://127.0.0.1:8000/), you should see the dev server in your browser (Make sure to open a new tab). Whenever you make changes to your server it will autorestart and so it supports iterative dev process. To make things easy, we will include the comman to open the server as a background process in a function called `dev_sever` so that we can call it with ease later in the notebook." ] }, { "cell_type": "code", "collapsed": false, "input": [ "class dev_server(object):\n", " def __init__(self):\n", " self.server = 'no_server'\n", " def start(self):\n", " '''\n", " starts the server\n", " '''\n", " import subprocess\n", " self.server = subprocess.Popen([\"python\", \"manage.py\", \"runserver\"])\n", " print \"Im running!\"\n", " def end(self):\n", " '''\n", " ends the sever\n", " '''\n", " if self.server == 'no_server':\n", " print \"there is no sever!\"\n", " else:\n", " self.server.terminate()\n", " print \"I've Stopped.\" " ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 34 }, { "cell_type": "code", "collapsed": false, "input": [ "dev_server = dev_server() # instantiate our object" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 35 }, { "cell_type": "code", "collapsed": false, "input": [ "dev_server.start()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Im running!\n" ] } ], "prompt_number": 39 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Creating a New Application" ] }, { "cell_type": "code", "collapsed": false, "input": [ "#Uncomment to run for the first time, to create your first app hello_world\n", "#!manage.py startapp hello_world" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 11 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Add our new hello_world app to our site, by adding it to the installed_apps in tutorial project settings.py file" ] }, { "cell_type": "markdown", "metadata": {}, "source": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# save and overwrite the file. After you add Hello_world to the installed_apps method, execute the cell and it will save by using the code below. \n", "%%writefile settings.py\n", "\n", "# Django settings for mysite project.\n", "\n", "DEBUG = True\n", "TEMPLATE_DEBUG = DEBUG\n", "\n", "ADMINS = (\n", " # ('Your Name', 'your_email@example.com'),\n", ")\n", "\n", "MANAGERS = ADMINS\n", "\n", "DATABASES = {\n", " 'default': {\n", " 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.\n", " 'NAME': '', # Or path to database file if using sqlite3.\n", " # The following settings are not used with sqlite3:\n", " 'USER': '',\n", " 'PASSWORD': '',\n", " 'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.\n", " 'PORT': '', # Set to empty string for default.\n", " }\n", "}\n", "\n", "# Hosts/domain names that are valid for this site; required if DEBUG is False\n", "# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts\n", "ALLOWED_HOSTS = []\n", "\n", "# Local time zone for this installation. Choices can be found here:\n", "# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name\n", "# although not all choices may be available on all operating systems.\n", "# In a Windows environment this must be set to your system time zone.\n", "TIME_ZONE = 'America/Chicago'\n", "\n", "# Language code for this installation. All choices can be found here:\n", "# http://www.i18nguy.com/unicode/language-identifiers.html\n", "LANGUAGE_CODE = 'en-us'\n", "\n", "SITE_ID = 1\n", "\n", "# If you set this to False, Django will make some optimizations so as not\n", "# to load the internationalization machinery.\n", "USE_I18N = True\n", "\n", "# If you set this to False, Django will not format dates, numbers and\n", "# calendars according to the current locale.\n", "USE_L10N = True\n", "\n", "# If you set this to False, Django will not use timezone-aware datetimes.\n", "USE_TZ = True\n", "\n", "# Absolute filesystem path to the directory that will hold user-uploaded files.\n", "# Example: \"/var/www/example.com/media/\"\n", "MEDIA_ROOT = ''\n", "\n", "# URL that handles the media served from MEDIA_ROOT. Make sure to use a\n", "# trailing slash.\n", "# Examples: \"http://example.com/media/\", \"http://media.example.com/\"\n", "MEDIA_URL = ''\n", "\n", "# Absolute path to the directory static files should be collected to.\n", "# Don't put anything in this directory yourself; store your static files\n", "# in apps' \"static/\" subdirectories and in STATICFILES_DIRS.\n", "# Example: \"/var/www/example.com/static/\"\n", "STATIC_ROOT = ''\n", "\n", "# URL prefix for static files.\n", "# Example: \"http://example.com/static/\", \"http://static.example.com/\"\n", "STATIC_URL = '/static/'\n", "\n", "# Additional locations of static files\n", "STATICFILES_DIRS = (\n", " # Put strings here, like \"/home/html/static\" or \"C:/www/django/static\".\n", " # Always use forward slashes, even on Windows.\n", " # Don't forget to use absolute paths, not relative paths.\n", ")\n", "\n", "# List of finder classes that know how to find static files in\n", "# various locations.\n", "STATICFILES_FINDERS = (\n", " 'django.contrib.staticfiles.finders.FileSystemFinder',\n", " 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n", "# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n", ")\n", "\n", "# Make this unique, and don't share it with anybody.\n", "SECRET_KEY = 'x&0!-(kxytngyi%d1190w18^6!vmsdfsob6oswzl^hj9qcv0ux'\n", "\n", "# List of callables that know how to import templates from various sources.\n", "TEMPLATE_LOADERS = (\n", " 'django.template.loaders.filesystem.Loader',\n", " 'django.template.loaders.app_directories.Loader',\n", "# 'django.template.loaders.eggs.Loader',\n", ")\n", "\n", "MIDDLEWARE_CLASSES = (\n", " 'django.middleware.common.CommonMiddleware',\n", " 'django.contrib.sessions.middleware.SessionMiddleware',\n", " 'django.middleware.csrf.CsrfViewMiddleware',\n", " 'django.contrib.auth.middleware.AuthenticationMiddleware',\n", " 'django.contrib.messages.middleware.MessageMiddleware',\n", " # Uncomment the next line for simple clickjacking protection:\n", " # 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n", ")\n", "\n", "ROOT_URLCONF = 'mysite.urls'\n", "\n", "# Python dotted path to the WSGI application used by Django's runserver.\n", "WSGI_APPLICATION = 'mysite.wsgi.application'\n", "\n", "TEMPLATE_DIRS = (\n", " # Put strings here, like \"/home/html/django_templates\" or \"C:/www/django/templates\".\n", " # Always use forward slashes, even on Windows.\n", " # Don't forget to use absolute paths, not relative paths.\n", ")\n", "\n", "INSTALLED_APPS = (\n", " 'django.contrib.auth',\n", " 'django.contrib.contenttypes',\n", " 'django.contrib.sessions',\n", " 'django.contrib.sites',\n", " 'django.contrib.messages',\n", " 'django.contrib.staticfiles',\n", " 'django.contrib.hello_world', #<--- here is our new added app!!!!!!!!!!!\n", " # Uncomment the next line to enable the admin:\n", " # 'django.contrib.admin',\n", " # Uncomment the next line to enable admin documentation:\n", " # 'django.contrib.admindocs',\n", ")\n", "\n", "# A sample logging configuration. The only tangible logging\n", "# performed by this configuration is to send an email to\n", "# the site admins on every HTTP 500 error when DEBUG=False.\n", "# See http://docs.djangoproject.com/en/dev/topics/logging for\n", "# more details on how to customize your logging configuration.\n", "LOGGING = {\n", " 'version': 1,\n", " 'disable_existing_loggers': False,\n", " 'filters': {\n", " 'require_debug_false': {\n", " '()': 'django.utils.log.RequireDebugFalse'\n", " }\n", " },\n", " 'handlers': {\n", " 'mail_admins': {\n", " 'level': 'ERROR',\n", " 'filters': ['require_debug_false'],\n", " 'class': 'django.utils.log.AdminEmailHandler'\n", " }\n", " },\n", " 'loggers': {\n", " 'django.request': {\n", " 'handlers': ['mail_admins'],\n", " 'level': 'ERROR',\n", " 'propagate': True,\n", " },\n", " }\n", "}\n", "\n" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Overwriting settings.py\n" ] } ], "prompt_number": 52 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Check the dev server at [http://127.0.0.1:8000/](http://127.0.0.1:8000/) again to make sure we installed the app correctly.\n", "\n", "If it runs, we did it!" ] }, { "cell_type": "code", "collapsed": false, "input": [ "dev_server.start()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Im running!\n" ] } ], "prompt_number": 53 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Add our new app's url's to our tutorial project:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%writefile urls.py\n", "from django.conf.urls.defaults import patterns, include, url\n", "# Uncomment the next two lines to enable the admin:\n", "# from django.contrib import admin\n", "# admin.autodiscover()\n", "urlpatterns = patterns( '' ,\n", " url(r '^hello_world/' , include( 'tutorial.hello_world.urls' )),\n", " url(r '^$' , 'tutorial.hello_world.views.welcome' ,name= 'hello_world-welcome' ),\n", "\t\t\t\t\t\t#url(r'^(?P.[^/]+)/(?P\\d+)/$', 'welcome', name='hello_world-welcome-name-age'),\n", "\n", "\t\t\t\t\t\t # Examples:\n", "\t\t\t\t\t\t # url(r'^$', 'tutorial.views.home', name='home'),\n", "\t\t\t\t\t\t # url(r'^tutorial/', include('tutorial.foo.urls')),\n", "\n", "\t\t\t\t\t\t # Uncomment the admin/doc line below to enable admin documentation:\n", "\t\t\t\t\t\t # url(r'^admin/doc/', include('django.contrib.admindocs.urls')),\n", "\n", "\t\t\t\t\t\t # Uncomment the next line to enable the admin:\n", "\t\t\t\t\t\t # url(r'^admin/', include(admin.site.urls)),\n", "\t\t\t\t\t\t)\n" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Overwriting urls.py\n" ] } ], "prompt_number": 54 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Create a new view in our Hello_World App" ] }, { "cell_type": "code", "collapsed": false, "input": [ "cd hello_world" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "C:\\Users\\Andrew\\Documents\\Kaggle\\tutorial\\django_tut\\tutorial\\hello_world\n" ] } ], "prompt_number": 59 }, { "cell_type": "code", "collapsed": false, "input": [ "ls" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ " Volume in drive C is OS\n", " Volume Serial Number is EA4A-2994\n", "\n", " Directory of C:\\Users\\Andrew\\Documents\\Kaggle\\tutorial\\django_tut\\tutorial\\hello_world\n", "\n", "06/11/2013 03:53 PM .\n", "06/11/2013 03:53 PM ..\n", "06/10/2013 04:50 PM 0 __init__.py\n", "06/11/2013 03:51 PM 172 __init__.pyc\n", "06/10/2013 04:50 PM 57 models.py\n", "06/10/2013 04:50 PM 383 tests.py\n", "06/11/2013 03:53 PM 844 views.py\n", "06/11/2013 03:53 PM 1,013 views.pyc\n", " 6 File(s) 2,469 bytes\n", " 2 Dir(s) 770,251,948,032 bytes free\n" ] } ], "prompt_number": 60 }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Open the views.py file, show below, and create our hello_world view:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "%%writefile test.py\n", "#Iam a test" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Writing test.py\n" ] } ], "prompt_number": 61 }, { "cell_type": "code", "collapsed": false, "input": [ "%%writefile views.py\n", "# Create your views here.\n", "from django.http import HttpResponse, HttpResponseForbidden\n", " def welcome(request, name=None, age=None):\n", " if name:\n", " # The URL pattern matches only numbers, so we're not handling the\n", " # ValueError that might happen if age isn't a numeric value.\n", " if not age or int(age) < 18:\n", " return HttpResponseForbidden( 'Grow up!' )\n", " response=HttpResponse()\n", " # Here we treat the response as a file-like object.\n", " response.write( \"Hi %s, are you %s?\" % (name,age,))\n", " # Here we just set a silly header (though a valid HTTP header\n", " # would be just as applicable!)\n", " response[ 'X-python-header' ]= 'That parrot is definitely dead.'\n", " return response\n", " else:\n", " # Here we pass it a string\n", " return HttpResponse( 'Hello!' )\n", " # Here we pass it a generator (just as an example)\n", " return HttpResponse(( '
%d' % (i) for i in xrange(1,1000)))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Overwriting views.py\n" ] } ], "prompt_number": 62 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Check out our new view by using !manage.py runserver and going to http://127.0.0.1:8000/" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Template Basics:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "cd .. " ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ " Volume in drive C is OS\n", " Volume Serial Number is EA4A-2994\n", "\n", " Directory of C:\\Users\\Andrew\\Documents\\Kaggle\\tutorial\\django_tut\n", "\n", "06/19/2013 03:53 PM .\n", "06/19/2013 03:53 PM ..\n", "06/13/2013 05:40 PM .ipynb_checkpoints\n", "06/19/2013 04:15 PM 24,290 django_tut.ipynb\n", "06/19/2013 03:36 PM 916 README.md\n", "06/19/2013 03:39 PM tutorial\n", " 2 File(s) 25,206 bytes\n", " 4 Dir(s) 770,260,766,720 bytes free\n" ] } ], "prompt_number": 66 }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "###Version Control" ] }, { "cell_type": "code", "collapsed": false, "input": [ "cd C:\\Users\\Andrew\\Documents\\Kaggle\\tutorial\\django_tut" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "C:\\Users\\Andrew\\Documents\\Kaggle\\tutorial\\django_tut\n" ] } ], "prompt_number": 67 }, { "cell_type": "code", "collapsed": false, "input": [ "!git add django_tut.ipynb" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 68 }, { "cell_type": "code", "collapsed": false, "input": [ "!git commit" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "[master 430928e] added templates section\n", " 1 file changed, 61 insertions(+), 6 deletions(-)\n" ] } ], "prompt_number": 69 }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }