Scott Baker | dcc9bee | 2014-07-13 16:21:38 -0700 | [diff] [blame] | 1 | from django.views.generic import View |
| 2 | from django.conf.urls import patterns, url |
| 3 | import os, sys |
| 4 | import inspect |
| 5 | import importlib |
Scott Baker | 88e3437 | 2014-07-13 11:46:36 -0700 | [diff] [blame] | 6 | |
Scott Baker | dcc9bee | 2014-07-13 16:21:38 -0700 | [diff] [blame] | 7 | # XXX based on core/dashboard/views/__init__.py |
| 8 | |
| 9 | # Find all modules in the current directory that have descendents of the View |
| 10 | # object, and add them as globals to this module. Also, build up a list of urls |
| 11 | # based on the "url" field of the view classes. |
| 12 | |
| 13 | urlpatterns=[] |
| 14 | |
| 15 | sys_path_save = sys.path |
| 16 | try: |
| 17 | # __import__() and importlib.import_module() both import modules from |
| 18 | # sys.path. So we make sure that the path where we can find the views is |
| 19 | # the first thing in sys.path. |
| 20 | view_dir = os.path.dirname(os.path.abspath(__file__)) |
| 21 | sys.path = [view_dir] + sys.path |
| 22 | view_urls = [] |
| 23 | for fn in os.listdir(view_dir): |
| 24 | pathname = os.path.join(view_dir,fn) |
| 25 | if os.path.isfile(pathname) and fn.endswith(".py") and (fn!="__init__.py"): |
| 26 | module = __import__(fn[:-3]) |
| 27 | for classname in dir(module): |
| 28 | c = getattr(module, classname, None) |
| 29 | |
| 30 | if inspect.isclass(c) and issubclass(c, View) and (classname not in globals()): |
| 31 | globals()[classname] = c |
| 32 | |
| 33 | method_kind = getattr(c, "method_kind", None) |
| 34 | method_name = getattr(c, "method_name", None) |
| 35 | if method_kind and method_name: |
| 36 | view_urls.append( (method_kind, method_name, classname, c) ) |
| 37 | |
| 38 | for view_url in view_urls: |
| 39 | if view_url[0] == "list": |
Scott Baker | db236c3 | 2014-07-13 17:36:19 -0700 | [diff] [blame^] | 40 | urlpatterns.append(url(r'^' + view_url[1] + '/$', view_url[3].as_view(), name=view_url[1]+'list')) |
Scott Baker | dcc9bee | 2014-07-13 16:21:38 -0700 | [diff] [blame] | 41 | elif view_url[0] == "detail": |
Scott Baker | db236c3 | 2014-07-13 17:36:19 -0700 | [diff] [blame^] | 42 | urlpatterns.append(url(r'^' + view_url[1] + '/(?P<pk>[a-zA-Z0-9\-]+)/$', view_url[3].as_view(), name=view_url[1]+'detail')) |
Scott Baker | dcc9bee | 2014-07-13 16:21:38 -0700 | [diff] [blame] | 43 | |
| 44 | finally: |
| 45 | sys.path = sys_path_save |