Signal when all urls are loaded in Django
<p>I want to perform magic on all url patterns of django:</p>

<p>If they don't have a name, then I want to give them an automated name.</p>

<p>Unfortunately django seems to load the url patterns lazy. </p>

<p>Implementing this magic-add-name-method is easy and not part of this question.</p>

<p>The problem: Where to call this method? I need to call this method after all urls have been loaded and before the first request gets handled.</p>

<p>Code should work for Django 1.9 and Django 1.10.</p>

<h1>Background</h1>

<p>Django deprecated the use of import-strings like this (<a href="https://code.djangoproject.com/ticket/22384" rel="nofollow">Deprecate the ability to reverse by dotted path)</a></p>

<pre><code>reverse('myapp.views.my_view')
</code></pre>

<p>I have a large legacy code base, and I don't like typing and maintaining redundant characters.</p>

<p>I want all urls without a name to have the name of their corresponding import-string.</p>

<p>Example in urls.py:</p>

<pre><code>url(r'^.../.../(?P&lt;pk&gt;[^/]+)/$', views.my_view))
</code></pre>

<p>I want to set the name of this url automatically to 'myapp.views.my_view'.</p>

<p>I wouldn't use signals to change the created urls after the fact but instead write a drop in replacement wrapper for <code>django.conf.urls.url</code>:</p>

<pre><code>def url(*args, **kwargs):
    if 'name' not in kwargs:
        kwargs['name'] = modulename(args[1])  # Returns something like 'polls.indexview'

    return django.conf.urls.url(*args, **kwargs)
</code></pre>

<p>That you can then use like</p>

<pre><code># from django.conf.urls import url  # Removed to enable auto-naming
from autonameroutes.urls import url

from . import views

app_name = 'polls'
urlpatterns = [
    url(r'^$', views.IndexView.as_view(), name='index'),
    url(r'^(?P&lt;pk&gt;\d+)/$', views.DetailView.as_view(), name='detail'),
    ...
]
</code></pre>

<p>The logic should be essentially the same as when changing all routes in the system, but you'd have more control when you want to use it and the change would be more obvious to the developer maintaining the code later on.</p>

python django django-urls django-signals