You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

views.py 16KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. import inspect
  2. from importlib import import_module
  3. from pathlib import Path
  4. from django.apps import apps
  5. from django.conf import settings
  6. from django.contrib import admin
  7. from django.contrib.admin.views.decorators import staff_member_required
  8. from django.contrib.admindocs import utils
  9. from django.contrib.admindocs.utils import (
  10. replace_named_groups, replace_unnamed_groups,
  11. )
  12. from django.core.exceptions import ImproperlyConfigured, ViewDoesNotExist
  13. from django.db import models
  14. from django.http import Http404
  15. from django.template.engine import Engine
  16. from django.urls import get_mod_func, get_resolver, get_urlconf
  17. from django.utils.decorators import method_decorator
  18. from django.utils.inspect import (
  19. func_accepts_kwargs, func_accepts_var_args, get_func_full_args,
  20. method_has_no_args,
  21. )
  22. from django.utils.translation import gettext as _
  23. from django.views.generic import TemplateView
  24. from .utils import get_view_name
  25. # Exclude methods starting with these strings from documentation
  26. MODEL_METHODS_EXCLUDE = ('_', 'add_', 'delete', 'save', 'set_')
  27. class BaseAdminDocsView(TemplateView):
  28. """
  29. Base view for admindocs views.
  30. """
  31. @method_decorator(staff_member_required)
  32. def dispatch(self, request, *args, **kwargs):
  33. if not utils.docutils_is_available:
  34. # Display an error message for people without docutils
  35. self.template_name = 'admin_doc/missing_docutils.html'
  36. return self.render_to_response(admin.site.each_context(request))
  37. return super().dispatch(request, *args, **kwargs)
  38. def get_context_data(self, **kwargs):
  39. return super().get_context_data(**{
  40. **kwargs,
  41. **admin.site.each_context(self.request),
  42. })
  43. class BookmarkletsView(BaseAdminDocsView):
  44. template_name = 'admin_doc/bookmarklets.html'
  45. class TemplateTagIndexView(BaseAdminDocsView):
  46. template_name = 'admin_doc/template_tag_index.html'
  47. def get_context_data(self, **kwargs):
  48. tags = []
  49. try:
  50. engine = Engine.get_default()
  51. except ImproperlyConfigured:
  52. # Non-trivial TEMPLATES settings aren't supported (#24125).
  53. pass
  54. else:
  55. app_libs = sorted(engine.template_libraries.items())
  56. builtin_libs = [('', lib) for lib in engine.template_builtins]
  57. for module_name, library in builtin_libs + app_libs:
  58. for tag_name, tag_func in library.tags.items():
  59. title, body, metadata = utils.parse_docstring(tag_func.__doc__)
  60. title = title and utils.parse_rst(title, 'tag', _('tag:') + tag_name)
  61. body = body and utils.parse_rst(body, 'tag', _('tag:') + tag_name)
  62. for key in metadata:
  63. metadata[key] = utils.parse_rst(metadata[key], 'tag', _('tag:') + tag_name)
  64. tag_library = module_name.split('.')[-1]
  65. tags.append({
  66. 'name': tag_name,
  67. 'title': title,
  68. 'body': body,
  69. 'meta': metadata,
  70. 'library': tag_library,
  71. })
  72. return super().get_context_data(**{**kwargs, 'tags': tags})
  73. class TemplateFilterIndexView(BaseAdminDocsView):
  74. template_name = 'admin_doc/template_filter_index.html'
  75. def get_context_data(self, **kwargs):
  76. filters = []
  77. try:
  78. engine = Engine.get_default()
  79. except ImproperlyConfigured:
  80. # Non-trivial TEMPLATES settings aren't supported (#24125).
  81. pass
  82. else:
  83. app_libs = sorted(engine.template_libraries.items())
  84. builtin_libs = [('', lib) for lib in engine.template_builtins]
  85. for module_name, library in builtin_libs + app_libs:
  86. for filter_name, filter_func in library.filters.items():
  87. title, body, metadata = utils.parse_docstring(filter_func.__doc__)
  88. title = title and utils.parse_rst(title, 'filter', _('filter:') + filter_name)
  89. body = body and utils.parse_rst(body, 'filter', _('filter:') + filter_name)
  90. for key in metadata:
  91. metadata[key] = utils.parse_rst(metadata[key], 'filter', _('filter:') + filter_name)
  92. tag_library = module_name.split('.')[-1]
  93. filters.append({
  94. 'name': filter_name,
  95. 'title': title,
  96. 'body': body,
  97. 'meta': metadata,
  98. 'library': tag_library,
  99. })
  100. return super().get_context_data(**{**kwargs, 'filters': filters})
  101. class ViewIndexView(BaseAdminDocsView):
  102. template_name = 'admin_doc/view_index.html'
  103. def get_context_data(self, **kwargs):
  104. views = []
  105. urlconf = import_module(settings.ROOT_URLCONF)
  106. view_functions = extract_views_from_urlpatterns(urlconf.urlpatterns)
  107. for (func, regex, namespace, name) in view_functions:
  108. views.append({
  109. 'full_name': get_view_name(func),
  110. 'url': simplify_regex(regex),
  111. 'url_name': ':'.join((namespace or []) + (name and [name] or [])),
  112. 'namespace': ':'.join((namespace or [])),
  113. 'name': name,
  114. })
  115. return super().get_context_data(**{**kwargs, 'views': views})
  116. class ViewDetailView(BaseAdminDocsView):
  117. template_name = 'admin_doc/view_detail.html'
  118. @staticmethod
  119. def _get_view_func(view):
  120. urlconf = get_urlconf()
  121. if get_resolver(urlconf)._is_callback(view):
  122. mod, func = get_mod_func(view)
  123. try:
  124. # Separate the module and function, e.g.
  125. # 'mymodule.views.myview' -> 'mymodule.views', 'myview').
  126. return getattr(import_module(mod), func)
  127. except ImportError:
  128. # Import may fail because view contains a class name, e.g.
  129. # 'mymodule.views.ViewContainer.my_view', so mod takes the form
  130. # 'mymodule.views.ViewContainer'. Parse it again to separate
  131. # the module and class.
  132. mod, klass = get_mod_func(mod)
  133. return getattr(getattr(import_module(mod), klass), func)
  134. def get_context_data(self, **kwargs):
  135. view = self.kwargs['view']
  136. view_func = self._get_view_func(view)
  137. if view_func is None:
  138. raise Http404
  139. title, body, metadata = utils.parse_docstring(view_func.__doc__)
  140. title = title and utils.parse_rst(title, 'view', _('view:') + view)
  141. body = body and utils.parse_rst(body, 'view', _('view:') + view)
  142. for key in metadata:
  143. metadata[key] = utils.parse_rst(metadata[key], 'model', _('view:') + view)
  144. return super().get_context_data(**{
  145. **kwargs,
  146. 'name': view,
  147. 'summary': title,
  148. 'body': body,
  149. 'meta': metadata,
  150. })
  151. class ModelIndexView(BaseAdminDocsView):
  152. template_name = 'admin_doc/model_index.html'
  153. def get_context_data(self, **kwargs):
  154. m_list = [m._meta for m in apps.get_models()]
  155. return super().get_context_data(**{**kwargs, 'models': m_list})
  156. class ModelDetailView(BaseAdminDocsView):
  157. template_name = 'admin_doc/model_detail.html'
  158. def get_context_data(self, **kwargs):
  159. model_name = self.kwargs['model_name']
  160. # Get the model class.
  161. try:
  162. app_config = apps.get_app_config(self.kwargs['app_label'])
  163. except LookupError:
  164. raise Http404(_("App %(app_label)r not found") % self.kwargs)
  165. try:
  166. model = app_config.get_model(model_name)
  167. except LookupError:
  168. raise Http404(_("Model %(model_name)r not found in app %(app_label)r") % self.kwargs)
  169. opts = model._meta
  170. title, body, metadata = utils.parse_docstring(model.__doc__)
  171. title = title and utils.parse_rst(title, 'model', _('model:') + model_name)
  172. body = body and utils.parse_rst(body, 'model', _('model:') + model_name)
  173. # Gather fields/field descriptions.
  174. fields = []
  175. for field in opts.fields:
  176. # ForeignKey is a special case since the field will actually be a
  177. # descriptor that returns the other object
  178. if isinstance(field, models.ForeignKey):
  179. data_type = field.remote_field.model.__name__
  180. app_label = field.remote_field.model._meta.app_label
  181. verbose = utils.parse_rst(
  182. (_("the related `%(app_label)s.%(data_type)s` object") % {
  183. 'app_label': app_label, 'data_type': data_type,
  184. }),
  185. 'model',
  186. _('model:') + data_type,
  187. )
  188. else:
  189. data_type = get_readable_field_data_type(field)
  190. verbose = field.verbose_name
  191. fields.append({
  192. 'name': field.name,
  193. 'data_type': data_type,
  194. 'verbose': verbose or '',
  195. 'help_text': field.help_text,
  196. })
  197. # Gather many-to-many fields.
  198. for field in opts.many_to_many:
  199. data_type = field.remote_field.model.__name__
  200. app_label = field.remote_field.model._meta.app_label
  201. verbose = _("related `%(app_label)s.%(object_name)s` objects") % {
  202. 'app_label': app_label,
  203. 'object_name': data_type,
  204. }
  205. fields.append({
  206. 'name': "%s.all" % field.name,
  207. "data_type": 'List',
  208. 'verbose': utils.parse_rst(_("all %s") % verbose, 'model', _('model:') + opts.model_name),
  209. })
  210. fields.append({
  211. 'name': "%s.count" % field.name,
  212. 'data_type': 'Integer',
  213. 'verbose': utils.parse_rst(_("number of %s") % verbose, 'model', _('model:') + opts.model_name),
  214. })
  215. methods = []
  216. # Gather model methods.
  217. for func_name, func in model.__dict__.items():
  218. if inspect.isfunction(func) or isinstance(func, property):
  219. try:
  220. for exclude in MODEL_METHODS_EXCLUDE:
  221. if func_name.startswith(exclude):
  222. raise StopIteration
  223. except StopIteration:
  224. continue
  225. verbose = func.__doc__
  226. verbose = verbose and (
  227. utils.parse_rst(utils.trim_docstring(verbose), 'model', _('model:') + opts.model_name)
  228. )
  229. # Show properties and methods without arguments as fields.
  230. # Otherwise, show as a 'method with arguments'.
  231. if isinstance(func, property):
  232. fields.append({
  233. 'name': func_name,
  234. 'data_type': get_return_data_type(func_name),
  235. 'verbose': verbose or ''
  236. })
  237. elif method_has_no_args(func) and not func_accepts_kwargs(func) and not func_accepts_var_args(func):
  238. fields.append({
  239. 'name': func_name,
  240. 'data_type': get_return_data_type(func_name),
  241. 'verbose': verbose or '',
  242. })
  243. else:
  244. arguments = get_func_full_args(func)
  245. # Join arguments with ', ' and in case of default value,
  246. # join it with '='. Use repr() so that strings will be
  247. # correctly displayed.
  248. print_arguments = ', '.join([
  249. '='.join([arg_el[0], *map(repr, arg_el[1:])])
  250. for arg_el in arguments
  251. ])
  252. methods.append({
  253. 'name': func_name,
  254. 'arguments': print_arguments,
  255. 'verbose': verbose or '',
  256. })
  257. # Gather related objects
  258. for rel in opts.related_objects:
  259. verbose = _("related `%(app_label)s.%(object_name)s` objects") % {
  260. 'app_label': rel.related_model._meta.app_label,
  261. 'object_name': rel.related_model._meta.object_name,
  262. }
  263. accessor = rel.get_accessor_name()
  264. fields.append({
  265. 'name': "%s.all" % accessor,
  266. 'data_type': 'List',
  267. 'verbose': utils.parse_rst(_("all %s") % verbose, 'model', _('model:') + opts.model_name),
  268. })
  269. fields.append({
  270. 'name': "%s.count" % accessor,
  271. 'data_type': 'Integer',
  272. 'verbose': utils.parse_rst(_("number of %s") % verbose, 'model', _('model:') + opts.model_name),
  273. })
  274. return super().get_context_data(**{
  275. **kwargs,
  276. 'name': '%s.%s' % (opts.app_label, opts.object_name),
  277. 'summary': title,
  278. 'description': body,
  279. 'fields': fields,
  280. 'methods': methods,
  281. })
  282. class TemplateDetailView(BaseAdminDocsView):
  283. template_name = 'admin_doc/template_detail.html'
  284. def get_context_data(self, **kwargs):
  285. template = self.kwargs['template']
  286. templates = []
  287. try:
  288. default_engine = Engine.get_default()
  289. except ImproperlyConfigured:
  290. # Non-trivial TEMPLATES settings aren't supported (#24125).
  291. pass
  292. else:
  293. # This doesn't account for template loaders (#24128).
  294. for index, directory in enumerate(default_engine.dirs):
  295. template_file = Path(directory) / template
  296. if template_file.exists():
  297. with template_file.open() as f:
  298. template_contents = f.read()
  299. else:
  300. template_contents = ''
  301. templates.append({
  302. 'file': template_file,
  303. 'exists': template_file.exists(),
  304. 'contents': template_contents,
  305. 'order': index,
  306. })
  307. return super().get_context_data(**{
  308. **kwargs,
  309. 'name': template,
  310. 'templates': templates,
  311. })
  312. ####################
  313. # Helper functions #
  314. ####################
  315. def get_return_data_type(func_name):
  316. """Return a somewhat-helpful data type given a function name"""
  317. if func_name.startswith('get_'):
  318. if func_name.endswith('_list'):
  319. return 'List'
  320. elif func_name.endswith('_count'):
  321. return 'Integer'
  322. return ''
  323. def get_readable_field_data_type(field):
  324. """
  325. Return the description for a given field type, if it exists. Fields'
  326. descriptions can contain format strings, which will be interpolated with
  327. the values of field.__dict__ before being output.
  328. """
  329. return field.description % field.__dict__
  330. def extract_views_from_urlpatterns(urlpatterns, base='', namespace=None):
  331. """
  332. Return a list of views from a list of urlpatterns.
  333. Each object in the returned list is a two-tuple: (view_func, regex)
  334. """
  335. views = []
  336. for p in urlpatterns:
  337. if hasattr(p, 'url_patterns'):
  338. try:
  339. patterns = p.url_patterns
  340. except ImportError:
  341. continue
  342. views.extend(extract_views_from_urlpatterns(
  343. patterns,
  344. base + str(p.pattern),
  345. (namespace or []) + (p.namespace and [p.namespace] or [])
  346. ))
  347. elif hasattr(p, 'callback'):
  348. try:
  349. views.append((p.callback, base + str(p.pattern), namespace, p.name))
  350. except ViewDoesNotExist:
  351. continue
  352. else:
  353. raise TypeError(_("%s does not appear to be a urlpattern object") % p)
  354. return views
  355. def simplify_regex(pattern):
  356. r"""
  357. Clean up urlpattern regexes into something more readable by humans. For
  358. example, turn "^(?P<sport_slug>\w+)/athletes/(?P<athlete_slug>\w+)/$"
  359. into "/<sport_slug>/athletes/<athlete_slug>/".
  360. """
  361. pattern = replace_named_groups(pattern)
  362. pattern = replace_unnamed_groups(pattern)
  363. # clean up any outstanding regex-y characters.
  364. pattern = pattern.replace('^', '').replace('$', '').replace('?', '')
  365. if not pattern.startswith('/'):
  366. pattern = '/' + pattern
  367. return pattern