[Answer]-Django: How to map urls to views dynamically with or without urls.py

0👍

✅

The urlpatterns variable is just Python, so if you can determine which callables you want to map to URLs you can automate it:

import inspect
import views

urlpatterns = [url(r'^%s$' % name, view) for name, view in views.__dict__.items()
               if callable(view) and
               inspect.getargspec(view)[0][0] == 'request']

But think carefully before doing so – automatically exposing all your views as URLs can open up parts of your app you didn’t intend to make public. The inspect argspec check above is a tiny step towards not accidentally opening up too much, but I wouldn’t want to rely on it too deeply.

1👍

The $ sign at the end of each URL stands for an exact match at the end

For example,

url(r'^do_foo$', views.do_foo)

will match only /do_foo whereas

url(r'^do_foo', views.do_foo)

will match

doo_foo/hello

doo_foo/abcd/bar

You can use this to reduce the size of your urls.py

You can’t get rid of urls.py entirely, but can map all urls to the same view function using

You can map all urls to the same view function using

url(r'', views.do_foo)

Leave a comment