iA


Importing Data From Google Docs Into Django, Step Two: Setting up your Django project

by Andy Boyle.

You are being very responsible by using a virtual environment.

Now that you’re using virtual environments and have many other fun tools installed, let’s move on to getting the Django projects started on your local machine. On my local machine, I put all of my projects in a directory called Code in my user directory. So if you don’t have an area created for your projects on your local machine, that’s one place to put it. To make that directory, type this in your terminal while in your user directory:

mkdir Code
cd Code

You just made that directory, and cd Code means you changed directories to Code. In here is where we will create our Google spreadsheet importer project in Django. Now, let’s make sure you’re in the right virtual environment by typing:

workon gdocs_importer

Now that you’re here, let’s just install Django and create a basic project. Installing Django takes a moment, so watch me tell a movie spoiler to my cat after typing the next line:

pip install Django==1.5

That installed software for Django 1.5, which is what this tutorial will use. Now let’s create our Django project using the django software you just installed:
django-admin.py startproject gdocs_importer

Now let’s cd into that directory and see what’s there:

cd gdocs_importer
ls

You should see a directory called gdocs_importer and a file called manage.py. Now we’re going to create some more files. I’ll tell you about them after you make them.

touch requirements.txt
touch gdocs_importer/__init__.py
touch gdocs_importer/models.py
touch gdocs_importer/views.py

First, we created a requirements.txt file. This is where we will include all of the site packages for your virtual environment to install. Then, inside the gdocs_importer directory, we created a models.py and views.py. These will be used to describe your database schema and how to display data.

Let’s take a look at the requirements.txt. Let’s throw this in there:

Django==1.5
fabric==1.4.3
gdata==2.0.17
geopy==0.95.1
gevent==0.13.8
greenlet==0.4.0
gunicorn==0.14.6
psycopg2==2.3.2
pycrypto==2.3
python-dateutil==2.1
python-memcached

Now let’s install all of these site packages. It’ll take a few minutes, but you’ll know when it’s finished when it shows you your normal command prompt.

pip install -r requirements.txt

It’ll skip over the Django one, as we already installed that previously. We’re not going to use all of these, but some of them will be useful if I plan on expanding this tutorial into explaining how to put this project on a live server, so we may as well install them.

Lastly, something optional is creating a local_settings.py in your gdocs_importer directory. I like to throw some things into local_settings.py from my main settings.py file, so if you’re using git on github (which you maybe should be) you won’t accidentally send any passwords or other things you want to keep hidden from the world. You do this by making sure your local_settings.py isn’t permitted to be added to your .git (Google it), and then add this to the top of your local settings.py:

from local_settings import *

Anywho, that’s a bit higher level stuff, so don’t worry if you don’t want to do that, as it won’t be necessarily for this project running on your local machine. Open up the settings.py file in gdocs_importer directory in your code editor of choice. You’ll want to start editing things so they look lik the code below,or the code in this gist. Feel free to copy and paste, but make sure you first copy your SECRET_KEY from your settings.py, store it elsewhere for a second, and put it where it belongs once you copy and paste it.

import django
import os
 
DJANGO_ROOT = os.path.dirname(os.path.realpath(django.__file__))
SITE_ROOT = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
 
DEBUG = True
TEMPLATE_DEBUG = DEBUG
 
ADMINS = (
    # ('Your Name', 'your_email@example.com'),
)
 
MANAGERS = ADMINS
 
DATABASES = {
    'default': {
        'NAME': 'gdocs_importer',
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'HOST': 'localhost',
        'PORT': '5432'
    },
}
 
# 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 = False
 
# 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',
)
 
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'o1v*eup$vkkldvomosh(#p87x)l)vin--$nfut!5z^6dksiwi6'
 
# 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',
)
 
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 = 'gdocs_importer.urls'
 
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'gdocs_importer.wsgi.application'
 
TEMPLATE_DIRS = (
    # Always use forward slashes, even on Windows.
    # Don't forget to use absolute paths, not relative paths.
    SITE_ROOT + "/templates",
)
 
INSTALLED_APPS = (
    'gdocs_importer',
    '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',
)
 
# 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,
    'formatters': {
        'verbose': {
            'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'simple'
        },
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        'gdocs_importer': {
            'handlers': ['console'],
            'level': 'DEBUG',
            'propagate': True,
        },
    }
}

Now your settings.py file should be able to find your database when you need to use it, and the Django app can find your gdocs_importer app.

Let’s open up that gdocs_importer/__init__.py file. Throw this in there:

from django.conf import settings

import logging

logger = logging.getLogger(__name__)

This is so we can properly log our debug code to our terminal window when we later run the management command. It’ll make sense then, I promise.

In the next post, I’ll be explaining how to set up your Google doc and the Django models.py to go with it.