Getting started with Django

Note taking software mac free best

I’ve been going through quite a bit of changes in my life lately – and as a part of that, my home blog (not this one – the personal things) will be moving to http://www.rachelblum.com.

And since I felt like I need more experience with web frameworks in general, I’m not sticking with my trusty wordpress. It does all the things I want it to do, but it was time to try something new: Django.

It was surprisingly easy to get started – most of my troubles came from the facts that I’ve skipped steps in the tutorials here or there, and then got flabbergasted when things didn’t work. Well, it’s all sorted out so far, but there’s one nifty trick I’d really like to share. Django has all its settings in a settings.py file, and it needs to change depending where you deploy and what your backend database is. That doesn’t work well with the idea of version control – so I modified the settings so you can get settings per machine.

At the bottom of settings.py, add the following code:

import socket
hostname = socket.gethostname().replace(‘.’,‘_’)
hostname = hostname.replace(‘-’,‘_’).lower()
exec “from config.%s import *” % hostname  
 

Notes

  1. I put all my configurations into a separate config module. I just like things clean – you can certainly keep them with the rest of your python.
  2. I know that exec is evil, but I really couldn’t figure out how to do this with __import__ instead. Any tips appreciated
  3. The mangling of gethostname() via replace() gets rid of invalid characters that import can’t handle. Also, it’s only split over two lines so I don’t get ugly line breaks.

All those per-host files should only contain host-specific settings. With exactly one development and one production machine, that’s certainly not too much duplication. And yet, I split it up into production.py and development.py – again, just because it looks a little bit cleaner1 (And I might get a new development machine at some point…)

So the config file for my local development machine right now only says

from config.development import *
 

I’ve been tempted to add a base.py for shared settings into the mix, but at some point, I probably should go back to developing as opposed to housekeeping.

knowledge management

Try the Note taking app for developers.
Bookmark the permalink.