Skip to main content

Automatically reload your browser in development.

Project description

https://img.shields.io/github/actions/workflow/status/adamchainz/django-browser-reload/main.yml.svg?branch=main&style=for-the-badge https://img.shields.io/badge/Coverage-100%25-success?style=for-the-badge https://img.shields.io/pypi/v/django-browser-reload.svg?style=for-the-badge https://img.shields.io/badge/code%20style-black-000000.svg?style=for-the-badge pre-commit

Automatically reload your browser in development.


Work smarter and faster with my book Boost Your Django DX which covers django-browser-reload and many other tools. I wrote django-browser-reload whilst working on the book!


Requirements

Python 3.9 to 3.13 supported.

Django 4.2 to 5.2 supported.

WSGI supported on all Django versions. ASGI supported on Django 4.2+.

Your browser needs to support:

  • EventSource - universally available.

  • SharedWorker - available on Chrome, Edge, Firefox, and Opera for a long time. Available on Safari since version 16 (2022-09-12).

Installation

  1. Install with pip:

    python -m pip install django-browser-reload
  2. Ensure you have "django.contrib.staticfiles" in your INSTALLED_APPS.

  3. Add django-browser-reload to your INSTALLED_APPS:

    INSTALLED_APPS = [
        ...,
        "django_browser_reload",
        ...,
    ]
  4. Include the app URLs in your root URLconf:

    from django.urls import include, path
    
    urlpatterns = [
        ...,
        path("__reload__/", include("django_browser_reload.urls")),
    ]

    You can use another prefix if required.

  5. Add the middleware:

    MIDDLEWARE = [
        # ...
        "django_browser_reload.middleware.BrowserReloadMiddleware",
        # ...
    ]

    The middleware should be listed after any others that encode the response, such as Django’s GZipMiddleware.

    The middleware automatically inserts the required script tag on HTML responses before </body> when DEBUG is True. It does so to every HTML response, meaning it will be included on Django’s debug pages, admin pages, etc. If you want more control, you can instead insert the script tag in your templates—see below.

All done! 📯

For faster and more efficient reloading, also set up Django’s built-in Watchman support.

What It Does

When DEBUG is True, the template tag includes a small script. This script connects back to the development server and will automatically reload when static assets or templates are modified, or after runserver restarts. The reload only happens in the most recently opened tab.

Example Project

See the example project in the example/ directory of the GitHub repository. Start it up and modify its files to see the reloading in action.

Template Tag

If the middleware doesn’t work for you, you can also use a template tag to insert the script on relevant pages. The template tag has both Django templates and Jinja versions, and only outputs the script tag when DEBUG is True.

For Django Templates, load the tag and use it in your base template. The tag can go anywhere, but it’s best just before </body>:

{% load django_browser_reload %}

...

    {% django_browser_reload_script %}
  </body>
</html>

To add django-browser-reload to Django’s admin, do so in a template called admin/base_site.html:

{% extends "admin/base_site.html" %}

{% load django_browser_reload %}

{% block extrahead %}
    {{ block.super }}
    {% django_browser_reload_script %}
{% endblock %}

This follows Django’s documentation on extending an overridden template.

For Jinja Templates, you need to perform two steps. First, load the tag function into the globals of your custom environment:

# myproject/jinja2.py
from jinja2 import Environment
from django_browser_reload.jinja import django_browser_reload_script


def environment(**options):
    env = Environment(**options)
    env.globals.update(
        {
            # ...
            "django_browser_reload_script": django_browser_reload_script,
        }
    )
    return env

Second, render the tag in your base template. It can go anywhere, but it’s best just before </body>:

...
    {{ django_browser_reload_script() }}
  </body>
</html>

Ta-da!

How It Works

Here’s a diagram:

                                     Browser

                             Tab 1    Tab 2     Tab N
                           listener  listener  listener
                                \       |       /
  Django                         \      |      /
                                  \     |     /
Events View --------------------> Shared worker

The template tag includes a listener script on each page. This listener script starts or connects to a SharedWorker, running a worker script. The worker script then connects to the events view in Django, using an EventSource to receive server-sent events.

This event source uses StreamingHttpResponse to send events to the worker. The view continues streaming events indefinitely, until disconnected. (This requires a thread and will not work if you use runserver’s --nothreading option.)

On a relevant event, the worker will reload the most recently connected tab. (It avoids reloading all tabs since that could be expensive.)

To reload when a template changes, django-browser-reload piggybacks on Django’s autoreloading infrastructure. An internal Django signal indicates when a template file has changed. The events view receives this signal and sends an event to the worker, which triggers a reload. There is no smart filtering - if any template file changes, the view is reloaded.

To reload when the server restarts, django-browser-reload uses a version ID. This ID is randomly generated when the view module is imported, so it will be different every time the server starts. When the server restarts, the worker’s EventSource reconnects with minimal delay. On connection, the events view sends the version ID, which the worker sees as different, so it triggers a reload.

The events view also sends the version ID every second to keep the connection alive.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_browser_reload-1.18.0.tar.gz (14.3 kB view details)

Uploaded Source

Built Distribution

django_browser_reload-1.18.0-py3-none-any.whl (12.2 kB view details)

Uploaded Python 3

File details

Details for the file django_browser_reload-1.18.0.tar.gz.

File metadata

File hashes

Hashes for django_browser_reload-1.18.0.tar.gz
Algorithm Hash digest
SHA256 c5f0b134723cbf2a0dc9ae1ee1d38e42db28fe23c74cdee613ba3ef286d04735
MD5 eb56432331cc1e2c8e47c7d702436eb3
BLAKE2b-256 3b4184eaa4f2b7f764e56e01c4ee49aa12bdea30ae50fd0d3ef7c2690b0c4ec2

See more details on using hashes here.

Provenance

The following attestation bundles were made for django_browser_reload-1.18.0.tar.gz:

Publisher: main.yml on adamchainz/django-browser-reload

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file django_browser_reload-1.18.0-py3-none-any.whl.

File metadata

File hashes

Hashes for django_browser_reload-1.18.0-py3-none-any.whl
Algorithm Hash digest
SHA256 ed4cc2fb83c3bf6c30b54107a1a6736c0b896e62e4eba666d81005b9f2ecf6f8
MD5 5a652e603ec2f647c9579e128fba7774
BLAKE2b-256 e49d1322dc4bce4982d1eadd3a62802c996ae0303aad13d9ad88c1d35025f73d

See more details on using hashes here.

Provenance

The following attestation bundles were made for django_browser_reload-1.18.0-py3-none-any.whl:

Publisher: main.yml on adamchainz/django-browser-reload

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page