Sunday, December 23, 2012

Django and sqlite3

This is a minor issue that bothered me for a while that I don't think the documentation makes clear.

When I was trying to set up an sqlite3 database with my django install, I was very confused because the tutorial I followed told me to enter in my settings.py file the location of the database. But I didn't have any database installed! Searching the internet returned several allusions to the fact that python2.5+ came with sqlite3 so I didn't have to install or download anything ... but if I didn't, how was I going to find where this elusive sqlite3 db was so that I could link django to it?

It turns out that django creates the database for you! So what you want to enter in the settings.py file is the link to the db file as you want it to be; for example: '/home/khalid/myproj/proj.db'

ProTip:

Consider defining the db url like so:

'NAME': os.path.join(os.path.dirname(__file__), '../proj.db').replace('\\','/')

This will make it so that the new db file is one directory above your settings.py file. If you want to do this, make sure you import settings.path at the top of your file.

Final Code:

import settings.path

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
        'NAME': os.path.join(os.path.dirname(__file__), '../proj.db').replace('\\','/'),  # Or path to database file if using sqlite3.
        'USER': '',                      # 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.
    }
}


Cheerio.

0 comments:

Post a Comment