Django: How to create a shared routing of URLs for views?

I have a pretty standard django application, and I am wondering how to configure URL routing so that I cannot explicitly map each URL to a view.

For example, let's say that I have the following views: Project, Links, Profile, Contact . I would prefer my urlpatterns look like this:

 (r'^Project/$', 'mysite.app.views.project'), (r'^Links/$', 'mysite.app.views.links'), (r'^Profile/$', 'mysite.app.views.profile'), (r'^Contact/$', 'mysite.app.views.contact'), 

And so on. In Pylons, it would be simple:

 map.connect(':controller/:action/:id') 

And it will automatically capture the right controller and function. Is there something similar in Django?

+6
python django pylons
source share
3 answers
 mods = ('Project','Links','Profile','Contact') urlpatterns = patterns('', *(('^%s/$'%n, 'mysite.app.views.%s'%n.lower()) for n in mods) ) 
+5
source share

If you really have a huge number of views, their explicit indication is not so bad, in terms of style.

However, you can shorten your example using the prefix argument to the patterns function:

 urlpatterns = patterns('mysite.app.views', (r'^Project/$', 'project'), (r'^Links/$', 'links'), (r'^Profile/$', 'profile'), (r'^Contact/$', 'contact'), ) 
+5
source share

You may be able to use the special viewing function in the following lines:

 def router(request, function, module): m =__import__(module, globals(), locals(), [function.lower()]) try: return m.__dict__[function.lower()](request) except KeyError: raise Http404() 

and then urlconf:

 (r'^(?P<function>.+)/$', router, {"module": 'mysite.app.views'}), 

This code is untested, but the general idea should work, although you should remember:

Explicit is better than implicit.

+5
source share

All Articles