I want to perform magic on all url patterns of django:
If they don't have a name, then I want to give them an automated name.
Unfortunately django seems to load the url patterns lazy.
Implementing this magic-add-name-method is easy and not part of this question.
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.
Code should work for Django 1.9 and Django 1.10.
Django deprecated the use of import-strings like this (Deprecate the ability to reverse by dotted path)
reverse('myapp.views.my_view')
I have a large legacy code base, and I don't like typing and maintaining redundant characters.
I want all urls without a name to have the name of their corresponding import-string.
Example in urls.py:
url(r'^.../.../(?P<pk>[^/]+)/$', views.my_view))
I want to set the name of this url automatically to 'myapp.views.my_view'.
I wouldn't use signals to change the created urls after the fact but instead write a drop in replacement wrapper for django.conf.urls.url
:
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)
That you can then use like
# 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<pk>\d+)/$', views.DetailView.as_view(), name='detail'),
...
]
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.