Christoffer Karlsson
Christoffer Karlsson

Reputation: 4943

Reload Django dev server when certain files changes

Is it possible to tell the Django development server to listen to changes on some files (not the regular Python files in the project, they already creates a reload) and reload if these files have changed?

Why do I want this? When my gulp-script builds the JS and CSS, it takes all files and appends a hash to them. My working file frontend/css/abc.css will be built to build/css/abc-hash123.css. This so that browsers are forced to reload the content if anything has changed since last deploy. When this builds, a manifest file is created that contains the mappings. In the settings in Django, I read this manifest file at start and get all these mappings (from this example here). If I change a file, it gets a new hash, and a new manifest is written. The mappings currently loaded into the memory are then wrong, and thus I need to force a reload of the development server to get the new mappings.

Clarification: I got comments on using a VCS. So just for clarification: I use a VCS and check in my abc.css. abc-hash123.css is automatically built as a part of the build system.

Upvotes: 1

Views: 1512

Answers (2)

Christoffer Karlsson
Christoffer Karlsson

Reputation: 4943

A bit of a hacky way, but I found a way to make force the Django server to reload on changes to the build directory. After some research on the Django autoreload module, I found that it only listen to changes on Python files, from modules that are loaded into sys.modules. So, I only needed to make the build directory a Python module:

In my build script (gulp), after I've built my files, I added a step to create the __init__.py file, to make the build directory a module. Then I also wrote a comment in this file that contains a time stamp, making it unique for each build:

fs.writeFile('./build/__init__.py', '#' + Date.now())

And then in my local.py (the settings to use locally), I simply import this new module, so it appears in sys.modules:

try:
    import build
except ImportError:
    print("Could not import from build folder. Will not auto reload when building new files.")

Upvotes: 0

Ivan
Ivan

Reputation: 6013

As far as doc goes this is not supported.

This is a bit hacky, but just touching (or changing the timestamp in any other way) some .py file or some other file that development server observes (e.g. settings.py) in your build will do the job.

Also as comments suggest, versioning is better left to a VCS.

Upvotes: 0

Related Questions