We will install django on home ~ dir.
mkdir ~/src cd ~/src wget http://www.djangoproject.com/download/1.3.1/tarball/ -O django.tar tar xvf django.tar cd Django-1.3.1
Install python and django in a specific directory. This will create bin & lib containing python&django in specified directory.
python setup.py install --home=~/devfs/opt/
Or install django on system's python directory (preferred):
sudo python setup.py install
This will install django to
[td@td-fed tutorial]$ ls /usr/lib/python2.7/site-packages/django/
set the PYTHONPATH env variable:
export PYTHONPATH=$HOME/lib/python export PATH=$HOME/bin:$PATH
Now verify that Django is installed and the right version is in your path:
python >>> import django >>> print django.get_version() 1.3.1
Virtualenv/Sandbox for python env to provide consistent project settings.
yum install python-pip.noarch yum install python-virtualenv.noarch
$ virtualenv mysite-env $ source mysite-env/bin/activate (mysite-env)$
(mysite-env)$ pip install Pinax
source: django tutorials.
Start Project:
$django-admin.py startproject mysite
Run webserver:
$python manage.py runserver
Configure Database:
$vim mysite/settings.py ... edit DATABASE section...
Create tables:
$python manage.py syncdb
Create Model:
python manage.py startapp polls ...edit polls/model.py...
class Poll(models.Model):
question = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
class Choice(models.Model):
poll = models.ForeignKey(Poll)
choice = models.CharField(max_length=200)
votes = models.IntegerField()
Activate model:
Edit settings.py, add 'polls'.
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
# 'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'polls',
)
See SQL code for 'polls':
python manage.py sql polls
Play around
Update DB:
python manage.py syncdb
Python API:
python manage.py shell >>> from polls.models import Poll, Choice ...see django cheatsheet for DB built-in functions... ...type Poll + <tab> to see how you can start... cool!!
It's important to add unicode() methods to your models, not only for your own sanity when dealing with the interactive prompt, but also because objects' representations are used throughout Django's automatically-generated admin.
class Poll(models.Model):
*** use <spaces> not <tabs> or python will throws unexpected indentation.
*** vim's :retab is useful for this.
# ...
def __unicode__(self):
return self.question
class Choice(models.Model):
# ...
def __unicode__(self):
return self.choice
import datetime
from django.utils import timezone
# ...
class Poll(models.Model):
# ...
def was_published_recently(self):
return self.pub_date >= timezone.now() - datetime.timedelta(days=1)