[Fixed]-How to properly runserver on different settings for Django?

13👍

For example I open SQL log in dev settings

  1. My file structure:
    create settings folder and mv original settings.py to settings/defaults.py
    enter image description here

  2. load defaults in init.py

# proj/proj/settings/__init__.py

from .defaults import *
  1. Edit dev.py
# proj/proj/settings/dev.py

from .defaults import *
DEBUG = True

# print sql to the console
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        }
    },
    'loggers': {
        'django.db.backends': {
            'handlers': ['console'],
            'propagate': True,
            'level': 'DEBUG',
        }
    },
}

  1. run in the python env
./manage.py runserver --settings proj.settings.dev

enter image description here

Django 2.1.7 | Mac

👤C.K.

9👍

Create a folder called config

config/
    commonsettings.py
    dev.py
    prod.py

make sure that in dev.py and prod.py you import everything from commonsettings.py like this:

from .commonsettings import * 

then if you want to run the dev.py settings:

python manage.py runserver --settings=config.dev

if you want to run prod.py:

python manage.py runserver --settings=config.prod

NOTE:

For more readable files many developers call their settings files: local.py (for the local settings) production.py (for the production settings) and base.py (the common settings for both)

Personally I place my setting files in:

config/
    settings/
        base.py
        local.py
        production.py
        test.py (For tests)
👤Tony

4👍

This solution works without extra arguments, and without having to replace/delete files across environments.

Make settings.py decide which file to load

Let’s assume your Django project is named MyDjangoApp.

Create the config/ dir in your Django project’s root dir, and one .py file per environment, e.g. like this:

config/
  local.py
  dev.py
  prod.py
MyDjangoApp/
  settings.py

There is no logical limit to the number of environments, I just added the three I usually have.

Then, inside MyDjangoApp/settings.py we can add the logic to choose which settings file to load.

"""
Django settings for MyDjangoApp project.
"""

import os

# Begin: Custom per-env settings
import socket
# Use the appropriate logic to understand "where" we're running
HOST = socket.gethostname() 
configs = {
    'localhost': 'local', # replace 'localhost' with whatever your machine name is
    'dev.mysite.com': 'dev',
    'www.mysite.com': 'production',
}

config = 'config.{}'.format(configs[HOST])

settings_module = __import__(config, globals(), locals(), ['MyDjangoApp', ])

try:
    for setting in dir(settings_module):
        # Only fully-uppercase variables are supposed to be settings
        if setting == setting.upper():
            locals()[setting] = getattr(settings_module, setting)
except Exception:
    # you may ignore this exception, the print() is for debugging purposes 
    print(Exception)

# End: Custom per-env settings

# ... the rest of the common settings go here

Please note: this logic chooses the settings file to load based on the hostname of the server which is running the Django app. It’s just an example- you can implement any other logic that works for you.

Change only what’s needed

The good news is, settings.py can still hold the vast majority of your settings, and the files inside config/ just need to contain the settings that change across your environments, e.g.:

  • DATABASES
  • DEBUG
  • ADMINS
  • LOGGING

Avoid –settings in the commandline

You can set the Django settings as a shell environment variable, like this:

export DJANGO_SETTINGS_MODULE=MyDjangoApp.settings

The best place to do this is in a .sh file; usually I create a file named env.sh file in the root dir of the Django project, and run it (once) just after activating the virtualenv.

File /env.sh contents

#!/usr/bin/env bash

export DJANGO_SETTINGS_MODULE=MyDjangoApp.settings

To run it from Terminal (Bash, or git-scm Bash on Windows):

. env.sh 

Then you can use ./manage.py runserver to start the Django server wherever you are.

Reference: https://code.djangoproject.com/wiki/SplitSettings#DevelopmentMachineDependantSettingsConfiguration

2👍

Put all your common configurations in the commonsettings.py file.

add following the line into the __init__.py file in the settings directory

from commonsettings import *

This makes every configuration in the commonsettings file available in all other files in the settings folder

start your server with

python3 manage.py runserver --settings=djangorest.settings.dev

1👍

Project Hierarchy will be

- djangorest
  - api
    - __init__.py
    - models.py
    - views.py
    - urls.py
    - etc..
  - djangorest
    - settings           (folder)
    - commonsettings.py
    - dev.py
    - prod.py
    - __init__.py
    - settings.py
    - urls.py
    - wsgi.py

After This run following commands before python manage.py runserver

export PYTHONPATH=$PWD

export DJANGO_SETTINGS_MODULE=djangorest.settings.dev

and Finally python manage.py runserver

0👍

Replace settings.py with dev.py on dev server and prod.py on production server.

now in init.py files write code

try:
    print("Trying import production.py settings...")
    from .prod import *
except ImportError:
    print("Trying import development.py settings...")
    from .dev import *

it find prod.py in production server and import it. On dev server it not find and prod.py and import dev.py

then you don’t need to specify configuration file name while running runserver command.

👤SuReSh

0👍

What I’ve always done is on the local env create a file called local_settings.py that can have it’s own database settings, static path and so on and at the end of the settings file include this

try:
    from local_settings import *#
except:
    pass

so on the server I always make sure not to import the local_settings and it separates the two nicely.

Leave a comment