Watching for file changes with StatReloader
The StatReloader is a utility in Django that automatically restarts the server whenever it detects changes in the project’s code files. This is especially useful during development as it saves time and effort in manually restarting the server every time a change is made.
To enable the StatReloader functionality, you need to add the following code in your project’s settings.py file:
DEBUG = True
if DEBUG:
import os
import sys
RUN_MAIN = bool(os.environ.get('RUN_MAIN', False))
if RUN_MAIN:
import ptvsd
ptvsd.enable_attach(address=('0.0.0.0', 8000))
ptvsd.wait_for_attach()
INTERNAL_IPS = [
'127.0.0.1',
]
MIDDLEWARE += [
'django_reloader.run_main_tick',
]
Let’s break down the above code:
- The
DEBUG
setting needs to be set asTrue
to enable the StatReloader in development mode. - The
RUN_MAIN
variable is responsible for restarting the server when changes are detected. - The
ptvsd
library enables remote debugging with Visual Studio Code (optional). - The
INTERNAL_IPS
setting allows the reloading process only for specified IP addresses. - The
django_reloader.run_main_tick
middleware is added to theMIDDLEWARE
list to activate the StatReloader functionality.
After adding the above code, you can start the server as usual:
python manage.py runserver
Now, whenever you make changes to your code files, the server will automatically restart, reflecting the latest changes. This allows you to see the effect of your modifications without manually restarting the server every time.
Note that the StatReloader may not work for all types of changes, such as modifications in the project’s static files. In such cases, you may need to manually restart the server.
This feature comes in handy when you are making frequent updates during development and want to save time and effort.