[Django]-Django settings based on IP or hostname

12đź‘Ť

âś…

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.

👤brianz

3đź‘Ť

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

Leave a comment