Create my project and call it mysite:
!django-admin.py startproject mysite
cd /home/agconti/my_dev/github/Atlatl_django/mysite
/home/agconti/my_dev/github/Atlatl_django/mysite
The line below clears all of the sqlite database so that I can run this notebook multiple times:
!python manage.py sqlclear houses | python manage.py dbshell
class dev_server(object):
'''
for easy server management
'''
def __init__(self):
self.server = 'no_server'
def start(self):
'''
starts the server
'''
import os
import subprocess
#get cwd
cdir = os.getcwd()
# change dir to make sure manage.py is avaliable
os.chdir('/home/agconti/my_dev/github/Atlatl_django/mysite')
# start dev server as a subprocess so we can still develop interactively
self.server = subprocess.Popen(["python", "manage.py", "runserver"])
#change dir back
os.chdir(cdir)
self.server = 'running'
print "Im running!\nGo here: http://127.0.0.1:8000/\nCurrent Working Dir: %s"%(cdir)
def link(self):
'''
outputs the server's link for convience
'''
if self.server == 'running':
print "Im running!\nGo here: http://127.0.0.1:8000"
else:
print "Sorry, I'm not running."
def link_admin(self):
'''
outputs the server's admin link for convience
'''
if self.server == 'running':
print "Im running!\nGo here: http://127.0.0.1:8000/admin/"
else:
print "Sorry, I'm not running."
def end(self):
'''
ends the sever
'''
if self.server == 'no_server':
print "there is no sever!"
else:
self.server.terminate()
self.server = 'no_server'
print "I've Stopped."
my_server = dev_server()
my_server.start()
Im running! Go here: http://127.0.0.1:8000/ Current Working Dir: /home/agconti/my_dev/github/Atlatl_django/mysite
Create my app and call it houses:
!python manage.py startapp houses
ls -l
total 52 drwxrwxr-x 4 agconti agconti 4096 Jul 21 15:55 houses/ -rw-r--r-- 1 agconti agconti 249 Jul 19 12:07 manage.py drwxrwxr-x 2 agconti agconti 4096 Jul 21 15:54 mysite/ -rw-r--r-- 1 agconti agconti 33792 Jul 21 16:26 sqlite3.db
cd houses/
/home/agconti/my_dev/github/Atlatl_django/mysite/houses
ll
total 48 -rw-rw-r-- 1 agconti 126 Jul 21 15:53 admin.py -rw-rw-r-- 1 agconti 346 Jul 21 15:54 admin.pyc -rw-r--r-- 1 agconti 0 Jul 19 12:34 __init__.py -rw-r--r-- 1 agconti 154 Jul 19 12:55 __init__.pyc drwxrwxr-x 3 agconti 4096 Jul 21 15:53 management/ -rw-r--r-- 1 agconti 398 Jul 21 15:53 models.py -rw-r--r-- 1 agconti 953 Jul 21 15:53 models.pyc drwxrwxrwx 3 agconti 4096 Jul 21 15:35 templates/ -rw-r--r-- 1 agconti 383 Jul 19 12:34 tests.py -rw-rw-r-- 1 agconti 140 Jul 21 15:53 urls.py -rw-rw-r-- 1 agconti 372 Jul 21 15:54 urls.pyc -rw-r--r-- 1 agconti 249 Jul 21 15:55 views.py -rw-r--r-- 1 agconti 621 Jul 21 15:55 views.pyc
%%writefile models.py
from django.db import models
# Create your models here.
class Owner(models.Model):
name = models.TextField(max_length=200, unique=True)
date_created = models.DateTimeField(auto_now_add=True, blank=True)
class House(models.Model):
address = models.TextField(max_length=200)
date_created = models.DateTimeField(auto_now_add=True, blank=True)
owner = models.OneToOneField(Owner)
Overwriting models.py
%%writefile admin.py
from django.contrib import admin
from houses.models import Owner, House
admin.site.register(House)
admin.site.register(Owner)
Overwriting admin.py
cd /home/agconti/my_dev/github/Atlatl_django/mysite/mysite
/home/agconti/my_dev/github/Atlatl_django/mysite/mysite
%%writefile settings.py
# Django settings for mysite project.
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '/home/agconti/my_dev/github/Atlatl_django/mysite/sqlite3.db', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
# 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.
# In a Windows environment this must be set to 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
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True
# If you set this to False, Django will not use timezone-aware datetimes.
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = ''
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
MEDIA_URL = ''
# Absolute path to the directory static files should be collected to.
# Don't put anything in this directory yourself; store your static files
# in apps' "static/" subdirectories and in STATICFILES_DIRS.
# Example: "/var/www/example.com/static/"
STATIC_ROOT = ''
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
STATIC_URL = '/static/'
# Additional locations of static files
STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)
# List of finder classes that know how to find static files in
# various locations.
STATICFILES_FINDERS = (
'django.contrib.staticfiles.finders.FileSystemFinder',
'django.contrib.staticfiles.finders.AppDirectoriesFinder',
# 'django.contrib.staticfiles.finders.DefaultStorageFinder',
)
# Make this unique, and don't share it with anybody.
SECRET_KEY = '(p(3gth07w54-0@+2^cx&@b5tdmd1p5v_&)(b0^8q-uop!^7(-'
# List of callables that know how to import templates from various sources.
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.Loader',
'django.template.loaders.app_directories.Loader',
# 'django.template.loaders.eggs.Loader',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
# Uncomment the next line for simple clickjacking protection:
# 'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
ROOT_URLCONF = 'mysite.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'mysite.wsgi.application'
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',
'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',
'houses' # register my new app
)
# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'filters': {
'require_debug_false': {
'()': 'django.utils.log.RequireDebugFalse'
}
},
'handlers': {
'mail_admins': {
'level': 'ERROR',
'filters': ['require_debug_false'],
'class': 'django.utils.log.AdminEmailHandler'
}
},
'loggers': {
'django.request': {
'handlers': ['mail_admins'],
'level': 'ERROR',
'propagate': True,
},
}
}
Overwriting settings.py
%%writefile urls.py
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
)
Overwriting urls.py
cd /home/agconti/my_dev/github/Atlatl_django/mysite
/home/agconti/my_dev/github/Atlatl_django/mysite
I'm using subprocess to preserve the interactive nature of the workbook:
import subprocess
subprocess.Popen(["python", "manage.py", "syncdb"])
<subprocess.Popen at 0x2891b90>
ll
total 52 drwxrwxr-x 4 agconti 4096 Jul 21 16:27 houses/ -rw-r--r-- 1 agconti 249 Jul 19 12:07 manage.py drwxrwxr-x 2 agconti 4096 Jul 21 16:27 mysite/ -rw-r--r-- 1 agconti 33792 Jul 21 16:27 sqlite3.db
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
Create The superuser account:
from django.contrib.auth.models import User
user = User.objects.create_user('andrew', 'andrew@agconti.com', 'password')
user.is_staff = True
user.save()
Check out the admin console
my_server.link_admin()
Im running! Go here: http://127.0.0.1:8000/admin/
Start Testing for first custom manage.py function:
# this lets me easily manipulate these models from within the notebook
from houses.models import Owner,House
o = Owner(name='Luke Skywalker')
o.save()
Owner.objects.all()
[<Owner: Owner object>]
jedi = Owner.objects.filter(id=1)
jedi.values()
[{'date_created': datetime.datetime(2013, 7, 21, 20, 27, 18, 851819, tzinfo=<UTC>), u'id': 1, 'name': u'Luke Skywalker'}]
jedi.delete()
Create the dir structure for the custom manage.py commands:
cd houses/
/home/agconti/my_dev/github/Atlatl_django/mysite/houses
%%bash
mkdir management
cd management
/home/agconti/my_dev/github/Atlatl_django/mysite/houses/management
%%writefile __init__.py
#Make management a Python package
Overwriting __init__.py
%%bash
mkdir commands
cd commands
/home/agconti/my_dev/github/Atlatl_django/mysite/houses/management/commands
%%writefile __init__.py
#Make commands a Python package
Overwriting __init__.py
%%writefile add_owner.py
#creates an add owner manage.py custom command
Overwriting add_owner.py
cd /home/agconti/my_dev/github/Atlatl_django/mysite/houses/management/commands
/home/agconti/my_dev/github/Atlatl_django/mysite/houses/management/commands
Add_Owner Function:
%%writefile add_owner.py
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from houses.models import Owner
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--name',
action='store',
type = 'string',
dest='name',
default=False,
help='Add Owner to owner Model'),
)
def handle(self, *args, **options):
if options['name']:
try:
o = Owner(name=options['name'])
o.save()
except Owner.unique_error_message:
raise CommandError('Owner "%s" already exists' % options['name'])
self.stdout.write('Successfully Added Owner Name="%s"' % options['name'])
Overwriting add_owner.py
cd ~/my_dev/github/Atlatl_django/mysite/
/home/agconti/my_dev/github/Atlatl_django/mysite
ll
total 52 drwxrwxr-x 4 agconti 4096 Jul 21 15:27 houses/ -rw-r--r-- 1 agconti 249 Jul 19 11:07 manage.py drwxrwxr-x 2 agconti 4096 Jul 21 15:27 mysite/ -rw-r--r-- 1 agconti 33792 Jul 21 15:27 sqlite3.db
Test custom function:
!python manage.py add_owner --name='Luke Skywalker'
Successfully Added Owner Name="Luke Skywalker"
o = Owner.objects.filter(id=1)
o.values_list()
[(1, u'Luke Skywalker', datetime.datetime(2013, 7, 21, 20, 27, 23, 464939, tzinfo=<UTC>))]
!python manage.py add_owner --name='Luke Skywalker'
IntegrityError: column name is not unique
o.delete()
Owner.objects.all()
[]
Add add_house function:
House.objects.all()
[]
# add Luke to test adding a house to an existing owner
o = Owner(name='Luke Skywalker')
o.save()
Owner.objects.all()[0].name
u'Luke Skywalker'
Owner.objects.all()[0].name # Luke added
u'Luke Skywalker'
o.name # beter notation
'Luke Skywalker'
House.objects.all() # check for existing houses
[]
o,create = Owner.objects.get_or_create(name='Luke Skywalker')
subprocess.Popen(["python", "manage.py", "syncdb"])
<subprocess.Popen at 0x34d83d0>
# add Luke's house
h,create = House.objects.get_or_create(address='Way to close to the Sand People', owner=o)
h.address
'Way to close to the Sand People'
h.owner.name
u'Luke Skywalker'
House.objects.all()
[<House: House object>]
House.objects.all()[0].owner.name # it does belong to Luke
u'Luke Skywalker'
cd /home/agconti/my_dev/github/Atlatl_django/mysite/houses/management/commands
/home/agconti/my_dev/github/Atlatl_django/mysite/houses/management/commands
%%writefile add_house.py
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import IntegrityError
from houses.models import House, Owner
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--owner',
action='store',
type = 'string',
dest='owner',
default=False,
help='Add Owner to owner Model'),
make_option('--address',
action='store',
type = 'string',
dest='address',
default=False,
help='Add house address to house model'),
)
def handle(self, *args, **options):
'''
'''
if (options['address'] != None) and (options['owner'] != None):
try:
# to add house and owner
o,create_owner = Owner.objects.get_or_create(name = options['owner'])
# if an owner was created sync the database
if (create_owner == True):
import subprocess
subprocess.Popen(["python", "manage.py", "syncdb"])
# create / get the house
o,create_house_owner = House.objects.get_or_create(address=options['address'], owner=(o))
if create_owner == True:
self.stdout.write(
'Successfully Added House: %s and Owner=%s'
% (options['address'], options['owner'])
)
elif create_house_owner == True:
self.stdout.write(
'Successfully Added House: %s to Owner=%s'
% (options['address'], options['owner'])
)
else:
self.stdout.write('method failed to create an owner or a house')
except IntegrityError:
self.stdout.write('There is already a house associated with that Owner')
else:
print 'Please include address AND owner!'
Overwriting add_house.py
cd ~/my_dev/github/Atlatl_django/mysite/
/home/agconti/my_dev/github/Atlatl_django/mysite
!python manage.py add_house --address="123 Main St." --owner='Mary'
Successfully Added House: 123 Main St. and Owner=Mary Creating tables ...
Owner.objects.all()
[<Owner: Owner object>, <Owner: Owner object>]
Owner.objects.all()[1].name
u'Mary'
Tests:
h = House.objects.all()
h.values()
[{'date_created': datetime.datetime(2013, 7, 21, 20, 27, 31, 472669, tzinfo=<UTC>), 'owner_id': 1, u'id': 1, 'address': u'Way to close to the Sand People'}, {'date_created': datetime.datetime(2013, 7, 21, 20, 28, 27, 606807, tzinfo=<UTC>), 'owner_id': 2, u'id': 2, 'address': u'123 Main St.'}]
o = Owner.objects.all()
o.values()
[{'date_created': datetime.datetime(2013, 7, 21, 20, 27, 28, 956290, tzinfo=<UTC>), u'id': 1, 'name': u'Luke Skywalker'}, {'date_created': datetime.datetime(2013, 7, 21, 20, 28, 27, 446686, tzinfo=<UTC>), u'id': 2, 'name': u'Mary'}]
Show_house Fucntion:
h = House.objects.all()
h
[<House: House object>, <House: House object>]
str(h[0].address)
'Way to close to the Sand People'
home_owner = h[0].owner
home_owner
<Owner: Owner object>
str(home_owner.name)
'Luke Skywalker'
Owner.objects.filter(name='Luke Skywalker')
[<Owner: Owner object>]
Owner(name='Mary')
<Owner: Owner object>
h = House.objects.filter(owner=Owner.objects.filter(name='Luke Skywalker'))
h[0].address
u'Way to close to the Sand People'
#get all of the fields associated with the model
fields = House.objects.model._meta.fields
fields
[<django.db.models.fields.AutoField: id>, <django.db.models.fields.TextField: address>, <django.db.models.fields.DateTimeField: date_created>, <django.db.models.fields.related.OneToOneField: owner>]
address = fields[1]
address.value_from_object(h[0])
u'Way to close to the Sand People'
for f in fields:
print '%s=[%s],'% (f.attname,f.value_from_object(h[0])),
id=[1], address=[Way to close to the Sand People], date_created=[2013-07-21 20:27:31.472669+00:00], owner_id=[1],
Owner.objects.get(name='Mary')
<Owner: Owner object>
House.objects.filter(address__contains='Main', owner=Owner.objects.get(name='Mary'))
[<House: House object>]
cd /home/agconti/my_dev/github/Atlatl_django/mysite/houses/management/commands
/home/agconti/my_dev/github/Atlatl_django/mysite/houses/management/commands
%%writefile show_house.py
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.forms.models import model_to_dict
from houses.models import House, Owner
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--owner',
action='store',
type = 'string',
dest='owner',
default=False,
help='Specify Owner to show'),
make_option('--addr-contains',
action='store',
type = 'string',
dest='addr',
default=False,
help='Specify Owner to show')
)
def handle(self, *args, **options):
'''
'''
#get fields for house model
fields = House.objects.model._meta.fields
if options['addr'] and options['owner']:
try:
house_querry = House.objects.filter(
address__contains=options['addr'],
owner=Owner.objects.get(name=options['owner'])
)
#print houses for owner to console
for i,val in enumerate(house_querry):
for f in fields:
self.stdout.write('%s=[%s],' % (f.attname,f.value_from_object(house_querry[i])), ending='')
self.stdout.write('')
except:
self.stdout.write(
'There is no house containing [%s] in the dataset Or there is no Owner=[%s]'
% (options['addr'], options['owner'])
)
elif options['owner']:
try:
#get houses for owner
house_querry = House.objects.filter(owner=Owner.objects.filter(name=options['owner']))
#print houses for owner to console
for i,val in enumerate(house_querry):
for f in fields:
self.stdout.write('%s=[%s],'
% (f.attname,f.value_from_object(house_querry[i])),
ending=''
)
self.stdout.write('')
except Owner.DoesNotExist:
self.stdout.write(
'Specified Owner=[%s] does not exist in the dataset'
% options['owner']
)
else:
#get all houses
house_querry = House.objects.all()
#print all houses to console
for i,val in enumerate(house_querry):
for f in fields:
self.stdout.write(
'%s=[%s],'
% (f.attname,f.value_from_object(house_querry[i])),
ending=''
)
self.stdout.write('')
Overwriting show_house.py
cd ~/my_dev/github/Atlatl_django/mysite/
/home/agconti/my_dev/github/Atlatl_django/mysite
!python manage.py show_house
id=[1],address=[Way to close to the Sand People],date_created=[2013-07-21 20:27:31.472669+00:00],owner_id=[1], id=[2],address=[123 Main St.],date_created=[2013-07-21 20:28:27.606807+00:00],owner_id=[2],
!python manage.py show_house --owner='Mary'
id=[2],address=[123 Main St.],date_created=[2013-07-21 20:28:27.606807+00:00],owner_id=[2],
!python manage.py show_house --owner='Mary' --addr-contains='Main'
id=[2],address=[123 Main St.],date_created=[2013-07-21 20:28:27.606807+00:00],owner_id=[2],
Delete_house command:
o = Owner(name='Star Trek Red Shirt') # soon to be deleted owner
o.save()
h = House(address='1 House of Cards Lane', owner=o) # soon to be gone house
h.save()
House.objects.filter(address__contains='Cards') #find it
[<House: House object>]
House.objects.filter(address__contains='Cards')[0].owner.name #Check it
u'Star Trek Red Shirt'
House.objects.filter(address__contains='Cards') #house to be deleted
[<House: House object>]
# Check if Owner has houses
len(House.objects.filter(owner=(House.objects.filter(address__contains='Cards')[0].owner)))
1
House.objects.filter(address__contains='Cards')[0].owner # Owner to be deleted
<Owner: Owner object>
#setup owner
o = House.objects.filter(address__contains='Cards')[0].owner
# delete house
House.objects.filter(address__contains='Cards').delete()
#delete owner if no houses
if len(House.objects.filter(owner=(o))) < 1:
o.delete()
cd /home/agconti/my_dev/github/Atlatl_django/mysite/houses/management/commands
/home/agconti/my_dev/github/Atlatl_django/mysite/houses/management/commands
%%writefile delete_house.py
from optparse import make_option
from exceptions import IndexError
from django.core.management.base import BaseCommand, CommandError
from houses.models import House, Owner
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option('--addr-contains',
action='store',
type = 'string',
dest='addr',
default=False,
help='Specify Owner to show'),
)
def handle(self, *args, **options):
'''
'''
if options['addr']:
# delete house
try:
#setup owner list
house_owners = []
# delete house
h = House.objects.filter(address__contains=options['addr'])
for i in h:
house_owners.append(i.owner)
i.delete()
self.stdout.write('House at [%s] was deleted' % i.address)
except:
self.stdout.write(
'There is no house containing [%s] in the dataset'
% options['addr']
)
#delete owner
try:
for o in house_owners:
# check their # of houses
if len(House.objects.filter(owner=(o))) < 1:
o.delete()
self.stdout.write('Owner [%s] was deleted' % o.name )
except IndexError:
self.stdout.write('There was an Error deleting Owner [%s]' % o.name )
Overwriting delete_house.py
cd ~/my_dev/github/Atlatl_django/mysite/
/home/agconti/my_dev/github/Atlatl_django/mysite
!python manage.py delete_house --addr-contains='Cards'
Delete house tests:
!python manage.py add_house --address='123 Lake Lane' --owner='Mr.Lake'
Successfully Added House: 123 Lake Lane and Owner=Mr.Lake Creating tables ...
Owner.objects.all()[2].name
u'Mr.Lake'
!python manage.py delete_house --addr-contains='Lake'
House at [123 Lake Lane] was deleted Owner [Mr.Lake] was deleted
Owner.objects.all()
[<Owner: Owner object>, <Owner: Owner object>]
House.objects.all()
[<House: House object>, <House: House object>]
Add two similar houses:
!python manage.py add_house --address='123 Lake Lane' --owner='Mr.Lake'
Successfully Added House: 123 Lake Lane and Owner=Mr.Lake Creating tables ...
!python manage.py add_house --address='124 Lake Lane' --owner='Mr.Lake' ## only when owner is manytomany and not onetoone
There is already a house associated with that Owner
!python manage.py delete_house --addr-contains='Lake'
House at [123 Lake Lane] was deleted Owner [Mr.Lake] was deleted
Handle Admin Site Error:
from django.contrib.sites.models import Site
if len(Site.objects.all()) ==0 :
Site.objects.create(pk=1)
Site.objects.all()[0].pk
1
my_server.link_admin()
Im running! Go here: http://127.0.0.1:8000/admin/
cd ~/my_dev/github/Atlatl_django/mysite/houses/
/home/agconti/my_dev/github/Atlatl_django/mysite/houses
%%writefile views.py
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello, world. You're at the houses index.")
Overwriting views.py
%%writefile urls.py
from django.conf.urls import patterns, url
from houses import views
urlpatterns = patterns('',
url(r'^$', views.index, name='index')
)
Overwriting urls.py
cd ~/my_dev/github/Atlatl_django/mysite/mysite/
/home/agconti/my_dev/github/Atlatl_django/mysite/mysite
%%writefile urls.py
from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'mysite.views.home', name='home'),
# url(r'^mysite/', include('mysite.foo.urls')),
# Uncomment the admin/doc line below to enable admin documentation:
# url(r'^admin/doc/', include('django.contrib.admindocs.urls')),
# Uncomment the next line to enable the admin:
url(r'^admin/', include(admin.site.urls)),
url(r'^houses/', include('houses.urls')),
)
Overwriting urls.py
ll
total 32 -rw-r--r-- 1 agconti 0 Jul 19 11:07 __init__.py -rw-r--r-- 1 agconti 154 Jul 19 11:13 __init__.pyc -rw-r--r-- 1 agconti 5430 Jul 21 15:27 settings.py -rw-r--r-- 1 agconti 3006 Jul 21 15:27 settings.pyc -rw-r--r-- 1 agconti 597 Jul 21 15:28 urls.py -rw-r--r-- 1 agconti 483 Jul 21 14:54 urls.pyc -rw-r--r-- 1 agconti 1419 Jul 19 11:07 wsgi.py -rw-r--r-- 1 agconti 1048 Jul 19 11:13 wsgi.pyc
Improve the view:
cd ~/my_dev/github/Atlatl_django/mysite/
/home/agconti/my_dev/github/Atlatl_django/mysite
Owner.objects.all()[0].house.address
u'Way to close to the Sand People'
for i in House.objects.all().order_by('owner'):
print i.owner.name, i.address
Luke Skywalker Way to close to the Sand People Mary 123 Main St.
cd ~/my_dev/github/Atlatl_django/mysite/houses/
/home/agconti/my_dev/github/Atlatl_django/mysite/houses
%%writefile views.py
from django.shortcuts import render
from houses.models import House, Owner
def index(request):
house_list = House.objects.all().order_by('owner')
context = {'house_list': house_list}
return render(request, 'houses/index.html', context)
Overwriting views.py
%%bash
mkdir templates
ll
total 48 -rw-rw-r-- 1 agconti 126 Jul 21 15:27 admin.py -rw-rw-r-- 1 agconti 346 Jul 21 14:54 admin.pyc -rw-r--r-- 1 agconti 0 Jul 19 11:34 __init__.py -rw-r--r-- 1 agconti 154 Jul 19 11:55 __init__.pyc drwxrwxr-x 3 agconti 4096 Jul 21 15:27 management/ -rw-r--r-- 1 agconti 398 Jul 21 15:27 models.py -rw-r--r-- 1 agconti 953 Jul 21 15:27 models.pyc drwxrwxrwx 3 agconti 4096 Jul 21 14:35 templates/ -rw-r--r-- 1 agconti 383 Jul 19 11:34 tests.py -rw-rw-r-- 1 agconti 140 Jul 21 15:28 urls.py -rw-rw-r-- 1 agconti 372 Jul 21 14:54 urls.pyc -rw-r--r-- 1 agconti 249 Jul 21 15:28 views.py -rw-r--r-- 1 agconti 621 Jul 21 14:55 views.pyc
cd templates
/home/agconti/my_dev/github/Atlatl_django/mysite/houses/templates
%%bash
mkdir houses
subilme index.html
cd /home/agconti/my_dev/github/Atlatl_django/mysite/houses/templates/houses
/home/agconti/my_dev/github/Atlatl_django/mysite/houses/templates/houses
ls -l
total 4 -rw-rw-r-- 1 agconti agconti 403 Jul 21 15:09 index.html
%%writefile index.html
<html>
<head>
<title>
What houses are in the Neigborhood?
</title>
<h1>What houses are in the Neigborhood?</h1>
</head>
<body>
{% if house_list %}
{% for house in house_list %}
<p>Owner: {{house.owner.name}}</p>
<ul>
<li>House address: {{ house.address }}</li>
</ul>
{% endfor %}
{% else %}
<p>No houses in the neighborhood.</p>
{% endif %}
</body>
</html>
Overwriting index.html
my_server.link()
Im running! Go here: http://127.0.0.1:8000
cd ~/my_dev/github/Atlatl_django/
/home/agconti/my_dev/github/Atlatl_django
!git add .
!git commit -a -m "final walk through"
[master 42b4f03] final walk through 10 files changed, 118 insertions(+), 98 deletions(-)
!git commit --amend -m "added webpage to show all houses and owners"
[master e7ab387] added webpage to show all houses and owners