Project: Initial study of Django framework, Dec 2008. Student: Kirby Urner, Coffee Shops Network Goal: accelerate acquisition of newer web dev skills Django uses tree of installed applications, each with optional url routing capability, to corresponding view functions, tasked with returning an HttpResponse. The SQL tables are optionally managed through an admin interface and with an object-relational mapping API, permitting filtering, inserts, updates in Python code, masking out most literal SQL. These data objects go into templates snarfed up into html (see below, just the one template so far) Grab the latest Django trunk from Subversion, do a symlink from python2.x/site-packages/django to path/trunk/django, and to /path/trunk/django-admin.py from /usr/local/bin (because already in path). If several pythons installed, you may want to customize executables such as manage.py to reflect that, or run with python2.x as prefix to executable module, e.g. python2.5 manage.py shell. Chief frustration so far: not being able to get image files to display off the disk, permissions issues etc. django-admin.py startproject mathy In mathy subdir (terminal): ./manager.py runserver (starts Django development server) http://127.0.0.1:8000/ (test in browser, different port OK) Then, populating an empty project with applications: kirby@dell:~/djapps/mathy$ ./manage.py startapp math_constants kirby@dell:~/djapps/mathy$ ./manage.py startapp trig kirby@dell:~/djapps/mathy$ ./manage.py startapp history INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'mathy.math_constants', 'mathy.trig', 'mathy.history', ) If defining a database in mathy/settings.py, then create mathy DB and a dAdmin user, if you don't have one already. Make sure you handle unicode issues. Django models don't specify unicode though Django itself uses it internally. create database mathy character set utf8 collate utf8_bin; # create user 'dAdmin'@'localhost' identified by 'password'; grant all on *.* to 'dAdmin'@'localhost' Then you'll want to create models of your SQL tables using models.py: ============================================ mathy/history/models.py from django.db import models # from django.core.files.storage import FileSystemStorage # Create your models here. class Mvps(models.Model): short_name = models.CharField('short_name', max_length=30) name = models.CharField('name', max_length=200) birth_year = models.IntegerField('yob') death_year = models.IntegerField('yod', null=True) def __unicode__(self): return '%s' % (self.short_name) ./manager.py syncdb ./manager.py shell >>> import populate # see below Now check to see what you've wrought: kirby@dell:~/djapps/mathy$ mysql -udAdmin -ptest Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 183 Server version: 5.0.51a-3ubuntu5.4 (Ubuntu) Type 'help;' or '\h' for help. Type '\c' to clear the buffer. mysql> use mathy; Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed mysql> show create table history_mvp; | history_mvps | CREATE TABLE `history_mvps` ( `id` int(11) NOT NULL auto_increment, `short_name` varchar(30) collate utf8_bin NOT NULL, `name` varchar(200) collate utf8_bin NOT NULL, `birth_year` int(11) NOT NULL, `death_year` int(11) default NULL, PRIMARY KEY (`id`) ) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_bin | mysql> desc history_mvps; +------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------+--------------+------+-----+---------+----------------+ | id | int(11) | NO | PRI | NULL | auto_increment | | short_name | varchar(30) | NO | | NULL | | | name | varchar(200) | NO | | NULL | | | birth_year | int(11) | NO | | NULL | | | death_year | int(11) | YES | | NULL | | +------------+--------------+------+-----+---------+----------------+ 5 rows in set (0.25 sec) mysql> select id, short_name, birth_year from history_mvps order by birth_year; +----+------------+------------+ | id | short_name | birth_year | +----+------------+------------+ | 5 | khw?razm? | 780 | | 2 | descartes | 1596 | | 1 | euler | 1707 | | 4 | kenjiro | 1902 | | 3 | kashiwara | 1947 | +----+------------+------------+ 5 rows in set (0.36 sec) mysql> \q Bye kirby@dell:~/djapps/mathy$ Dispatching to urls.py further down the tree, keeping one up top... ============================================ mathy/urls.py from django.conf.urls.defaults import * urlpatterns = patterns('', (r'^mathy/$', 'mathy.views.welcome'), (r'^mathy/math_constants/', include('mathy.math_constants.urls')), (r'^mathy/history/', include('mathy.history.urls')), (r'^mathy/trig/', include('mathy.trig.urls')), ) ============================================ mathy/admin.py from mathy.history.models import Mvps from django.contrib import admin admin.site.register(Mvps) ============================================ mathy/populate.py from mathy.history.models import Mvps p = Mvps(short_name="euler", name="Leonhard Euler", birth_year=1707, death_year=1783) p.save() p = Mvps(short_name="descartes", name="René Descartes", birth_year=1596, death_year=1650) p.save() [ more with non-Latin-1 characters not shown ] ============================================ mathy/history/urls.py from django.conf.urls.defaults import * urlpatterns = patterns('mathy.history.views', (r'mvp/all/$', 'list_all'), (r'mvp/(?P\w+)/$', 'cosmic_fish'), (r'event/$', 'event'), (r'mvp/$', 'mvp'), (r'', 'what_stuff'), ) ============================================ mathy/history/views.py from django.shortcuts import HttpResponse, render_to_response from mathy.history.models import Mvps def what_stuff(request): html = "

What Event or Player?


" return HttpResponse(html) def event(request): html = "

What Event?


" return HttpResponse(html) def mvp(request): html = "

What MVP?


" return HttpResponse(html) def cosmic_fish(request, **kwargs): sn = kwargs['wacko'] p = Mvps.objects.get(short_name = sn) html = "

%s: %s - %s


" % (p.name, p.birth_year, p.death_year) return HttpResponse(html) def list_all(request): all_mvps = Mvps.objects.all() return render_to_response('allmvps.html', {'all_mvps' : all_mvps}) ============================================ mathy/templates/allmvps.html All MVPs

MVPs

{% for item in all_mvps %} {% endfor %}
{{ item.name }} ({{ item.birth_year }} - {{ item.death_year }})

...or Python for that matter...

============================================ mathy/math_constants/urls.py from django.conf.urls.defaults import * urlpatterns = patterns('mathy.math_constants.views', (r'pi/$', 'get_pi'), (r'phi/$','get_phi'), (r'e/$', 'get_e'), (r'', 'what_constant'), ) ============================================ mathy/math_constants/views.py from django.shortcuts import HttpResponse from math import pi, e, sqrt phi = (1 + sqrt(5))/2 def what_constant(request): html = "

What Constant?


" return HttpResponse(html) def get_pi(request): html = "

%s


" % (pi,) return HttpResponse(html) def get_phi(request): html = "

%s


" % (phi,) return HttpResponse(html) def get_e(request): html = "

%s


" % (e,) return HttpResponse(html) ============================================ mathy/trig/urls.py from django.conf.urls.defaults import * urlpatterns = patterns('mathy.trig.views', (r'cos/$', 'get_cos'), (r'sin/$','get_sin'), (r'tan/$', 'get_tan'), (r'', 'what_function'), ) ============================================ mathy/trig/views.py from django.shortcuts import HttpResponse from math import sin, cos, tan, radians def what_function(request): html = "

What Constant?


" return HttpResponse(html) def get_sin(request): theangle = float(request.GET['angle']) html = "

%s(%s) = %s


" % ('sin', theangle, sin(radians(theangle))) return HttpResponse(html) def get_cos(request): theangle = float(request.GET['angle']) html = "

%s(%s) = %s


" % ('cos', theangle, cos(radians(theangle))) return HttpResponse(html) def get_tan(request): theangle = float(request.GET['angle']) html = "

%s(%s) = %s


" % ('tan', theangle, tan(radians(theangle))) return HttpResponse(html) ============================================ mathy/settings.py # Django settings for mathy project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@domain.com'), ) MANAGERS = ADMINS DATABASE_ENGINE = 'mysql' # 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'. DATABASE_NAME = 'mathy' # Or path to database file if using sqlite3. DATABASE_USER = 'dAdmin' # Not used with sqlite3. DATABASE_PASSWORD = 'test' # Not used with sqlite3. DATABASE_HOST = '' # Set to empty string for localhost. Not used with sqlite3. DATABASE_PORT = '' # Set to empty string for default. Not used with sqlite3. # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = True # Absolute path to the directory that holds media. # Example: "/home/media/media.lawrence.com/" MEDIA_ROOT = '' # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash if there is a path component (optional in other cases). # Examples: "http://media.lawrence.com", "http://example.com/media/" MEDIA_URL = '' # URL prefix for admin media -- CSS, JavaScript and images. Make sure to use a # trailing slash. # Examples: "http://foo.com/media/", "/media/". ADMIN_MEDIA_PREFIX = '/media/' # Make this unique, and don't share it with anybody. SECRET_KEY = 'gi&ud=0xa)9n^oq0(rm^!noancrc2knah6u(&_q=-%*2ry5v#1' # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( 'django.template.loaders.filesystem.load_template_source', 'django.template.loaders.app_directories.load_template_source', # 'django.template.loaders.eggs.load_template_source', ) MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', ) ROOT_URLCONF = 'mathy.urls' TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. ) INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'mathy.math_constants', 'mathy.trig', 'mathy.history', 'django.contrib.admin', )