cd /home/agconti/my_dev/github/Atlatl_django/mysite !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() ls -l cd houses/ ll %%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) %%writefile admin.py from django.contrib import admin from houses.models import Owner, House admin.site.register(House) admin.site.register(Owner) cd /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, }, } } %%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)), ) cd /home/agconti/my_dev/github/Atlatl_django/mysite import subprocess subprocess.Popen(["python", "manage.py", "syncdb"]) ll import os os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings' my_server.link_admin() # 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() jedi = Owner.objects.filter(id=1) jedi.values() jedi.delete() cd houses/ cd management %%writefile __init__.py #Make management a Python package cd commands %%writefile __init__.py #Make commands a Python package %%writefile add_owner.py #creates an add owner manage.py custom command cd /home/agconti/my_dev/github/Atlatl_django/mysite/houses/management/commands %%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']) cd ~/my_dev/github/Atlatl_django/mysite/ ll !python manage.py add_owner --name='Luke Skywalker' o = Owner.objects.filter(id=1) o.values_list() !python manage.py add_owner --name='Luke Skywalker' o.delete() Owner.objects.all() 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 Owner.objects.all()[0].name # Luke added o.name # beter notation House.objects.all() # check for existing houses o,create = Owner.objects.get_or_create(name='Luke Skywalker') subprocess.Popen(["python", "manage.py", "syncdb"]) # add Luke's house h,create = House.objects.get_or_create(address='Way to close to the Sand People', owner=o) h.address h.owner.name House.objects.all() House.objects.all()[0].owner.name # it does belong to Luke cd /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!' cd ~/my_dev/github/Atlatl_django/mysite/ !python manage.py add_house --address="123 Main St." --owner='Mary' Owner.objects.all() Owner.objects.all()[1].name h = House.objects.all() h.values() o = Owner.objects.all() o.values() h = House.objects.all() h str(h[0].address) home_owner = h[0].owner home_owner str(home_owner.name) Owner.objects.filter(name='Luke Skywalker') Owner(name='Mary') h = House.objects.filter(owner=Owner.objects.filter(name='Luke Skywalker')) h[0].address #get all of the fields associated with the model fields = House.objects.model._meta.fields fields address = fields[1] address.value_from_object(h[0]) for f in fields: print '%s=[%s],'% (f.attname,f.value_from_object(h[0])), Owner.objects.get(name='Mary') House.objects.filter(address__contains='Main', owner=Owner.objects.get(name='Mary')) cd /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('') cd ~/my_dev/github/Atlatl_django/mysite/ !python manage.py show_house !python manage.py show_house --owner='Mary' !python manage.py show_house --owner='Mary' --addr-contains='Main' 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.objects.filter(address__contains='Cards')[0].owner.name #Check it House.objects.filter(address__contains='Cards') #house to be deleted # Check if Owner has houses len(House.objects.filter(owner=(House.objects.filter(address__contains='Cards')[0].owner))) House.objects.filter(address__contains='Cards')[0].owner # Owner to be deleted #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 %%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 ) cd ~/my_dev/github/Atlatl_django/mysite/ !python manage.py delete_house --addr-contains='Cards' !python manage.py add_house --address='123 Lake Lane' --owner='Mr.Lake' Owner.objects.all()[2].name !python manage.py delete_house --addr-contains='Lake' Owner.objects.all() House.objects.all() !python manage.py add_house --address='123 Lake Lane' --owner='Mr.Lake' !python manage.py add_house --address='124 Lake Lane' --owner='Mr.Lake' ## only when owner is manytomany and not onetoone !python manage.py delete_house --addr-contains='Lake' from django.contrib.sites.models import Site if len(Site.objects.all()) ==0 : Site.objects.create(pk=1) Site.objects.all()[0].pk my_server.link_admin() cd ~/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.") %%writefile urls.py from django.conf.urls import patterns, url from houses import views urlpatterns = patterns('', url(r'^$', views.index, name='index') ) cd ~/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')), ) ll cd ~/my_dev/github/Atlatl_django/mysite/ Owner.objects.all()[0].house.address for i in House.objects.all().order_by('owner'): print i.owner.name, i.address cd ~/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) ll cd templates cd /home/agconti/my_dev/github/Atlatl_django/mysite/houses/templates/houses ls -l %%writefile index.html What houses are in the Neigborhood?

What houses are in the Neigborhood?

{% if house_list %} {% for house in house_list %}

Owner: {{house.owner.name}}

{% endfor %} {% else %}

No houses in the neighborhood.

{% endif %} my_server.link() cd ~/my_dev/github/Atlatl_django/ !git add . !git commit -a -m "final walk through" !git commit --amend -m "added webpage to show all houses and owners"