iA


Step Five: Setting up your database and settings.py file

by Andy Boyle.

We’ve got our models.py file figured out in Step Four. Next we need to set up a database for models.py to talk to, and then edit our settings.py file so it knows where everything lives.

First let’s set up a database in PostgreSQL via the command line, which you can also learn at this site. So, ssh into your server using a terminal app, like I showed you in Step One. Then we’re going to add a user who has the right permissions to interract with the database. Let’s call the user bobloblaw. Once you’re logged in, you make bobloblaw (or whatever) like this:

sudo adduser bobloblaw

Add a password and then remember it. Now we need to switch over to the postgresql user, which isn’t that hard. Type:  

sudo su postgres

Your command line will now have “postgres” in front of it. Next we need to open up the postgresql command line, which is simple, by typing:

psql template1

Well, now we need to add bobloblaw by typing:

CREATE USER bobloblaw WITH PASSWORD 'lawblog';

Remember the semi-colon at the end. It’s very important. Let’s create our table for firetracker. Type:

CREATE DATABASE firetracker;

And lastly we must give the database permissions to be used by bobloblaw:

GRANT ALL PRIVILEGES ON DATABASE firetracker to bobloblaw;

Woohoo! We did it! Now type \q to quit.

SETTING UP SETTINGS.PY

Now connect with your FTP client and go to /opt/django-projects/firetracker and open settings.py. This is sort of where you tell your app which database you’re using, where it lives, etc. Here’s how you should have it set up, but first read the code and then I’ll tell you about it:

# Django settings for firetracker project.

DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    ('Your Name', 'yourname@email.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'postgresql_psycopg2', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': 'firetracker',                      # Or path to database file if using sqlite3.
        'USER': 'bobloblaw',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        '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
TIME_ZONE = 'America/New_York'

# 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

# Absolute filesystem path to the directory that will hold user-uploaded files.
# 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 = ''

# HEY this next line? We will add something here in the next step. But for now, you can just leave in this place holder
ADMIN_MEDIA_PREFIX = 'http://s3.amazonaws.com/bucketname/projectname/admin/'

# Make this unique, and don't share it with anybody.
# This shouldn't actually say blah because you should use whatever was originally here
SECRET_KEY = 'blah'

# 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',
)

ROOT_URLCONF = 'firetracker.urls'

TEMPLATE_DIRS = ("/opt/django-projects/firetracker/templates"
    # 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.admin',
    'firetracker.fires',
)

# Ignore this next bit, but we will put something here later that you will like
from S3 import CallingFormat
DEFAULT_FILE_STORAGE = 'storages.backends.s3.S3Storage'
AWS_ACCESS_KEY_ID = 'your_access_key_id'
AWS_SECRET_ACCESS_KEY = 'your_secret_access_key'
AWS_STORAGE_BUCKET_NAME = 'andymboyle'
AWS_CALLING_FORMAT = CallingFormat.SUBDOMAIN
AWS_HEADERS = {
'Expires': 'Sat, 15 Apr 2012 20:00:00 GMT',
'Cache-Control': 'max-age=86400',
}
AWS_STORAGE_ACL = 'public-read'
# This next part, if you use gmail, enter in your email at gmail.com and your password
# This way we can send error messages to you and that is so much fun
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'youremail@email.com'
EMAIL_HOST_PASSWORD = 'yourpasswordgoeshere'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
}

WHAT THE HELL IS THIS SHIT

So a lot of this stuff may be over your head. Don’t worry, because it slowly makes sense once you see it in action. Most of it you can just leave alone, but there’s a few spots that you can edit now or will have to edit later. This code is how yours should sort of look, with you filling the blanks in later. The Debug = True bit is just so you can see errors when they happen. The ADMINS part should make sense — you want to be able to login to the admin with a name and whatnot. So put in your name and email.

The databases bit is the important part: You’re telling it to use postgresql and psycopg2, which is a fancy way of saying “Use this database backend, please.” Then you’re giving it the name of the database — remember that up there? — and the user that can access the database on the server.

Scroll down to SECRET_KEY. I threw blah in there as placeholder. Your current settings.py file has a long random string here, so you’ll want to use that instead of blah, obviously. TEMPLATE_DIRS is where we’re going to throw the template folder, which I will explain a later post. ADMIN_MEDIA_PREFIX I will teach you about in my next post.

Under INSTALLED_APPS we add the app we just created. See it there? ‘firetracker.fires’, is the code we add. We also added ‘django.contrib.admin’, as well, which I will explain in the next post.

The from S3 import CallingFormat won’t be used in this tutorial, but I thought you should have it. You use this if you want to add something to upload media, perhaps photos of people or fires. Who knows. But I wanted to leave it in there in case I expand this later.

And lastly, the part that begins with EMAIL_HOST will allow you to add an email client. This one is set up for gmail. I would highly suggest if you’re creating an app you make some sort of gmail account that’s called appnameisbroke@gmail.com and then forward it to yourself and any other developers on your team. This way, once a project is in production, you’ll get emails when stuff breaks. This is important.

So, you can copy the code from up there, or copy the code from here and put it into your settings.py file via your FTP client and text editor.

SYNCDB TIME HELLS YEAH

Now comes the awesomest part. Go into your /opt/django-projects/firetracker directory and type this:

python manage.py syncdb

If nothing’s broken, it’ll ask you to create a superuser. This will be a username to log into the admin later. Remember it. And then if a bunch of stuff runs across the screen and ends with something like “No fixtures found.” then you did it right! Go grab a beer and praise Jacob Kaplan-Moss because your goddamn syncdb worked!

So what did we do? We now made it so your app can talk with the database backend. Because we’re not going to be making any changes to the models.py file, we don’t have to worry about much. But if we were, you’d want to install South, which is a totally rad thing to install and allows you to make changes to your models without having to go into the database and doing SQL queries to drop tables and yatta yatta yatta. Just use South if you plan on editing this app.

Next we shall set up the views and some basic templates. I know, you’re excited and probably can’t wait, either.

No comments on ‘Step Five: Setting up your database and settings.py file’

Leave a Reply