Skip to main content

Django: Executing from Anywhere

One nice convenience would be to have a way to call from anywhere within a virtual environment.  For example, if I want to execute ' shell', it would be nice to be able to execute that from anywhere rather than having to change directory to where lives.

We can already run management commands from anywhere using django-admin by utilizing the --settings flag, but doing this requires a lot of typing. And wrapping the django-admin in a shell script seems inelegant somehow.

Instead, I wrote a small python script based off of  This can be placed in the ./bin directory in the virtualenv.  The DjangoManageSettings object is meant to be customized on a per project basis, and I intend to make it so it can be passed in from a file configuration somewhere.

Anyway, thought I would share.  I'm curious to see other approaches to this.

# ---------- ${VIRTUAL_ENV}/bin/ -------------------------
#!/usr/bin/env python

import os, sys
from import execute_manager

class DjangoManageSettings(object):

    def __init__(self):
        self.VENV_ROOT = os.getenv("VIRTUAL_ENV")
        # The name of the module that resides in
        # The path to the directory where the Django project lives. 
        # I made it relative to the virtualenv root. 
        self.PROJECT_PARENT_PATH = os.path.join(self.VENV_ROOT, "app")
        # The name of the django settings model in the project

dm_settings = DjangoManageSettings()

if not dm_settings.VENV_ROOT:
    print("A virtual environment must be activated before using this script.")

sys.path.insert(0, os.path.join(dm_settings.PROJECT_PARENT_PATH))
mod = __import__(dm_settings.PROJECT_NAME, globals(), locals(), 
settings = getattr(mod, dm_settings.SETTINGS_MODULE_NAME)

if __name__ == "__main__":


  1. You don't really have to pass the settings module as argument for `` on each call. Command `` also looks for the environment variable `DJANGO_SETTINGS_MODULE` to locate your settings module. And thus every virtualenv have a script named `activate` which gets invoked when activating the virtualenv, you can simple export `DJANGO_SETTINGS_MODULE` with the proper value.

    `` even allows you to use other names for your settings module than "settings". I maintain a separate settings module for each environment e.g. "project.settings.devel", "".

  2. Thanks the advice - didn't think of using the DJANGO_SETTINGS_MODULE, but that seems like a simpler solution. (To get this to work, I also needed to put my project on the Python Path.)
    Thank you again, Joe


Post a Comment

Popular posts from this blog

Django Docker and Celery

I've finally had the time to create a Django+Celery project that can be completely run using Docker and Docker Compose. I'd like to share some of the steps that helped me achieve this. I've created an example project that I've used to demo this process. The example project can be viewed here on Github.

To run this example, you will need to have a recent version of Docker and Docker Compose installed. I'm using Docker 17.03.1 and Docker Compose 1.11.2.

Let's take a look at one of the core files, the docker-compose.yml.   You'll notice that I have defined the following services:
db - the service running the Postgres database container, needed for the Django apprabbitmq - service running the RabbitMQ container, needed for queuing jobs submitted by Celeryapp - the service containing Django app containerworker - the service that runs the Celery worker containerweb - the service that runs the Nginx con…

Django Admin Override Save for Model

Sometimes it's nice to be able to add custom code to the save method of objects in the Django Admin.  So, when editing an object on the Admin object detail page (change form), adding the following method override to your ModelAdmin in will allow you to add custom code to the save function.

class MyModelAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): # custom stuff here
This is documented in the Django Docs, but I found it particularly useful.

Django: Using Caching to Track Online Users

Recently I wanted a simple solution to track whether a user is online on a given Django site.  The definition of "online" on a site is kind of ambiguous, so I'll define that a user is considered to be online if they have made any request to the site in the last five minutes.

I found that one approach is to use Django's caching framework to track when a user last accessed the site.  For example, upon each request, I can have a middleware set the current time as a cache value associated with a given user.  This allows us to store some basic information about logged-in user's online state without having to hit the database on each request and easily retrieve it by accessing the cache.

My approach below.  Comments welcome.

# add the middleware that you are about to create to settings MIDDLEWARE_CLASSES = ( .... 'middleware.activeuser_middleware.ActiveUserMiddleware', .... ) # Setup caching per Django docs. In actuality, you'd p…