Stuart Axon
Stuart Axon

Reputation: 1874

Django settings based on IP or hostname

I'd like to have something in my settings like

if ip in DEV_IPS:
   SOMESETTING = 'foo'
else:
   SOMESETTING = 'bar'

Is there an easy way to get the ip or hostname - also - is this is a bad idea ?

Upvotes: 3

Views: 5496

Answers (2)

brianz
brianz

Reputation: 7428

import socket
socket.gethostbyname(socket.gethostname())

However, I'd recommend against this and instead maintain multiple settings file for each environment you're working with.

settings/__init__.py
settings/qa.py 
settings/production.py

__init__.py has all of your defaults. At the top of qa.py, and any other settings file, the first line has:

from settings import *

followed by any overrides needed for that particular environment.

Upvotes: 12

Matt Williamson
Matt Williamson

Reputation: 40193

One method some shops use is to have an environment variable set on each machine. Maybe called "environment". In POSIX systems you can do something like ENVIRONMENT=production in the user's .profile file (this will be slightly different for each shell and OS). Then in settings.py you can do something like this:

import os

if os.environ['ENVIRONMENT'] == 'production':
    # Production
    DATABASE_ENGINE = 'mysql'
    DATABASE_NAME = ....
else:
    # Development

Upvotes: 3

Related Questions