Reload routes from code#

Problem#

A custom router backend reads URLs from a database table and you need to rebuild the URL set when a row changes.

Solution#

Call router_manager.reload() from a signal receiver on the relevant Django model. The framework rebuilds every backend from the current configuration, clears the Django URL resolver cache, and emits a router_reloaded signal.

Walkthrough#

Wire the receivers. Each receiver is decorated with @receiver at module top level, and AppConfig.ready imports the module so the decorators run once on startup.

notes/receivers.py#
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from next.urls import router_manager
from notes.models import Note

@receiver(post_save, sender=Note)
def reload_router_on_save(**kwargs) -> None:
    router_manager.reload()

@receiver(post_delete, sender=Note)
def reload_router_on_delete(**kwargs) -> None:
    router_manager.reload()

Import the receivers module from AppConfig.ready so the decorators run at startup.

notes/apps.py#
from django.apps import AppConfig

class NotesConfig(AppConfig):
    name = "notes"

    def ready(self) -> None:
        from notes import receivers  # imported for its receiver registrations

Each call rebuilds the backend list from the current NEXT_FRAMEWORK configuration, clears Django’s URL caches, and emits router_reloaded. Receivers should tolerate being invoked more than once when several writes batch into one task.

Observe the reload#

Long lived processes that cache URL references can listen to router_reloaded.

cache invalidation#
from django.dispatch import receiver
from next.urls.signals import router_reloaded

@receiver(router_reloaded)
def drop_url_cache(**kwargs) -> None:
    my_cache.clear()

Verification#

Add a row to the underlying table and confirm that the next request resolves the new URL without restarting the server.

See also#

See also

File router for the reload mechanics. URL router for the manager internals.