PageRenderTime 50ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 1ms

/django/views/debug.py

https://github.com/insane/django
Python | 1122 lines | 1032 code | 33 blank | 57 comment | 85 complexity | e2bd26a1f2a92b9c3ae134c1bf775d7c MD5 | raw file
Possible License(s): BSD-3-Clause
  1. from __future__ import unicode_literals
  2. import datetime
  3. import os
  4. import re
  5. import sys
  6. import types
  7. from django.conf import settings
  8. from django.http import (HttpResponse, HttpResponseServerError,
  9. HttpResponseNotFound, HttpRequest, build_request_repr)
  10. from django.template import Template, Context, TemplateDoesNotExist
  11. from django.template.defaultfilters import force_escape, pprint
  12. from django.utils.html import escape
  13. from django.utils.encoding import force_bytes, smart_text
  14. from django.utils.module_loading import import_by_path
  15. from django.utils import six
  16. HIDDEN_SETTINGS = re.compile('API|TOKEN|KEY|SECRET|PASS|PROFANITIES_LIST|SIGNATURE')
  17. CLEANSED_SUBSTITUTE = '********************'
  18. def linebreak_iter(template_source):
  19. yield 0
  20. p = template_source.find('\n')
  21. while p >= 0:
  22. yield p+1
  23. p = template_source.find('\n', p+1)
  24. yield len(template_source) + 1
  25. def cleanse_setting(key, value):
  26. """Cleanse an individual setting key/value of sensitive content.
  27. If the value is a dictionary, recursively cleanse the keys in
  28. that dictionary.
  29. """
  30. try:
  31. if HIDDEN_SETTINGS.search(key):
  32. cleansed = CLEANSED_SUBSTITUTE
  33. else:
  34. if isinstance(value, dict):
  35. cleansed = dict((k, cleanse_setting(k, v)) for k,v in value.items())
  36. else:
  37. cleansed = value
  38. except TypeError:
  39. # If the key isn't regex-able, just return as-is.
  40. cleansed = value
  41. return cleansed
  42. def get_safe_settings():
  43. "Returns a dictionary of the settings module, with sensitive settings blurred out."
  44. settings_dict = {}
  45. for k in dir(settings):
  46. if k.isupper():
  47. settings_dict[k] = cleanse_setting(k, getattr(settings, k))
  48. return settings_dict
  49. def technical_500_response(request, exc_type, exc_value, tb):
  50. """
  51. Create a technical server error response. The last three arguments are
  52. the values returned from sys.exc_info() and friends.
  53. """
  54. reporter = ExceptionReporter(request, exc_type, exc_value, tb)
  55. if request.is_ajax():
  56. text = reporter.get_traceback_text()
  57. return HttpResponseServerError(text, content_type='text/plain')
  58. else:
  59. html = reporter.get_traceback_html()
  60. return HttpResponseServerError(html, content_type='text/html')
  61. # Cache for the default exception reporter filter instance.
  62. default_exception_reporter_filter = None
  63. def get_exception_reporter_filter(request):
  64. global default_exception_reporter_filter
  65. if default_exception_reporter_filter is None:
  66. # Load the default filter for the first time and cache it.
  67. default_exception_reporter_filter = import_by_path(
  68. settings.DEFAULT_EXCEPTION_REPORTER_FILTER)()
  69. if request:
  70. return getattr(request, 'exception_reporter_filter', default_exception_reporter_filter)
  71. else:
  72. return default_exception_reporter_filter
  73. class ExceptionReporterFilter(object):
  74. """
  75. Base for all exception reporter filter classes. All overridable hooks
  76. contain lenient default behaviors.
  77. """
  78. def get_request_repr(self, request):
  79. if request is None:
  80. return repr(None)
  81. else:
  82. return build_request_repr(request, POST_override=self.get_post_parameters(request))
  83. def get_post_parameters(self, request):
  84. if request is None:
  85. return {}
  86. else:
  87. return request.POST
  88. def get_traceback_frame_variables(self, request, tb_frame):
  89. return list(six.iteritems(tb_frame.f_locals))
  90. class SafeExceptionReporterFilter(ExceptionReporterFilter):
  91. """
  92. Use annotations made by the sensitive_post_parameters and
  93. sensitive_variables decorators to filter out sensitive information.
  94. """
  95. def is_active(self, request):
  96. """
  97. This filter is to add safety in production environments (i.e. DEBUG
  98. is False). If DEBUG is True then your site is not safe anyway.
  99. This hook is provided as a convenience to easily activate or
  100. deactivate the filter on a per request basis.
  101. """
  102. return settings.DEBUG is False
  103. def get_post_parameters(self, request):
  104. """
  105. Replaces the values of POST parameters marked as sensitive with
  106. stars (*********).
  107. """
  108. if request is None:
  109. return {}
  110. else:
  111. sensitive_post_parameters = getattr(request, 'sensitive_post_parameters', [])
  112. if self.is_active(request) and sensitive_post_parameters:
  113. cleansed = request.POST.copy()
  114. if sensitive_post_parameters == '__ALL__':
  115. # Cleanse all parameters.
  116. for k, v in cleansed.items():
  117. cleansed[k] = CLEANSED_SUBSTITUTE
  118. return cleansed
  119. else:
  120. # Cleanse only the specified parameters.
  121. for param in sensitive_post_parameters:
  122. if param in cleansed:
  123. cleansed[param] = CLEANSED_SUBSTITUTE
  124. return cleansed
  125. else:
  126. return request.POST
  127. def get_traceback_frame_variables(self, request, tb_frame):
  128. """
  129. Replaces the values of variables marked as sensitive with
  130. stars (*********).
  131. """
  132. # Loop through the frame's callers to see if the sensitive_variables
  133. # decorator was used.
  134. current_frame = tb_frame.f_back
  135. sensitive_variables = None
  136. while current_frame is not None:
  137. if (current_frame.f_code.co_name == 'sensitive_variables_wrapper'
  138. and 'sensitive_variables_wrapper' in current_frame.f_locals):
  139. # The sensitive_variables decorator was used, so we take note
  140. # of the sensitive variables' names.
  141. wrapper = current_frame.f_locals['sensitive_variables_wrapper']
  142. sensitive_variables = getattr(wrapper, 'sensitive_variables', None)
  143. break
  144. current_frame = current_frame.f_back
  145. cleansed = {}
  146. if self.is_active(request) and sensitive_variables:
  147. if sensitive_variables == '__ALL__':
  148. # Cleanse all variables
  149. for name, value in tb_frame.f_locals.items():
  150. cleansed[name] = CLEANSED_SUBSTITUTE
  151. else:
  152. # Cleanse specified variables
  153. for name, value in tb_frame.f_locals.items():
  154. if name in sensitive_variables:
  155. value = CLEANSED_SUBSTITUTE
  156. elif isinstance(value, HttpRequest):
  157. # Cleanse the request's POST parameters.
  158. value = self.get_request_repr(value)
  159. cleansed[name] = value
  160. else:
  161. # Potentially cleanse only the request if it's one of the frame variables.
  162. for name, value in tb_frame.f_locals.items():
  163. if isinstance(value, HttpRequest):
  164. # Cleanse the request's POST parameters.
  165. value = self.get_request_repr(value)
  166. cleansed[name] = value
  167. if (tb_frame.f_code.co_name == 'sensitive_variables_wrapper'
  168. and 'sensitive_variables_wrapper' in tb_frame.f_locals):
  169. # For good measure, obfuscate the decorated function's arguments in
  170. # the sensitive_variables decorator's frame, in case the variables
  171. # associated with those arguments were meant to be obfuscated from
  172. # the decorated function's frame.
  173. cleansed['func_args'] = CLEANSED_SUBSTITUTE
  174. cleansed['func_kwargs'] = CLEANSED_SUBSTITUTE
  175. return cleansed.items()
  176. class ExceptionReporter(object):
  177. """
  178. A class to organize and coordinate reporting on exceptions.
  179. """
  180. def __init__(self, request, exc_type, exc_value, tb, is_email=False):
  181. self.request = request
  182. self.filter = get_exception_reporter_filter(self.request)
  183. self.exc_type = exc_type
  184. self.exc_value = exc_value
  185. self.tb = tb
  186. self.is_email = is_email
  187. self.template_info = None
  188. self.template_does_not_exist = False
  189. self.loader_debug_info = None
  190. # Handle deprecated string exceptions
  191. if isinstance(self.exc_type, six.string_types):
  192. self.exc_value = Exception('Deprecated String Exception: %r' % self.exc_type)
  193. self.exc_type = type(self.exc_value)
  194. def format_path_status(self, path):
  195. if not os.path.exists(path):
  196. return "File does not exist"
  197. if not os.path.isfile(path):
  198. return "Not a file"
  199. if not os.access(path, os.R_OK):
  200. return "File is not readable"
  201. return "File exists"
  202. def get_traceback_data(self):
  203. "Return a Context instance containing traceback information."
  204. if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist):
  205. from django.template.loader import template_source_loaders
  206. self.template_does_not_exist = True
  207. self.loader_debug_info = []
  208. for loader in template_source_loaders:
  209. try:
  210. source_list_func = loader.get_template_sources
  211. # NOTE: This assumes exc_value is the name of the template that
  212. # the loader attempted to load.
  213. template_list = [{
  214. 'name': t,
  215. 'status': self.format_path_status(t),
  216. } for t in source_list_func(str(self.exc_value))]
  217. except AttributeError:
  218. template_list = []
  219. loader_name = loader.__module__ + '.' + loader.__class__.__name__
  220. self.loader_debug_info.append({
  221. 'loader': loader_name,
  222. 'templates': template_list,
  223. })
  224. if (settings.TEMPLATE_DEBUG and
  225. hasattr(self.exc_value, 'django_template_source')):
  226. self.get_template_exception_info()
  227. frames = self.get_traceback_frames()
  228. for i, frame in enumerate(frames):
  229. if 'vars' in frame:
  230. frame['vars'] = [(k, force_escape(pprint(v))) for k, v in frame['vars']]
  231. frames[i] = frame
  232. unicode_hint = ''
  233. if self.exc_type and issubclass(self.exc_type, UnicodeError):
  234. start = getattr(self.exc_value, 'start', None)
  235. end = getattr(self.exc_value, 'end', None)
  236. if start is not None and end is not None:
  237. unicode_str = self.exc_value.args[1]
  238. unicode_hint = smart_text(unicode_str[max(start-5, 0):min(end+5, len(unicode_str))], 'ascii', errors='replace')
  239. from django import get_version
  240. c = {
  241. 'is_email': self.is_email,
  242. 'unicode_hint': unicode_hint,
  243. 'frames': frames,
  244. 'request': self.request,
  245. 'filtered_POST': self.filter.get_post_parameters(self.request),
  246. 'settings': get_safe_settings(),
  247. 'sys_executable': sys.executable,
  248. 'sys_version_info': '%d.%d.%d' % sys.version_info[0:3],
  249. 'server_time': datetime.datetime.now(),
  250. 'django_version_info': get_version(),
  251. 'sys_path' : sys.path,
  252. 'template_info': self.template_info,
  253. 'template_does_not_exist': self.template_does_not_exist,
  254. 'loader_debug_info': self.loader_debug_info,
  255. }
  256. # Check whether exception info is available
  257. if self.exc_type:
  258. c['exception_type'] = self.exc_type.__name__
  259. if self.exc_value:
  260. c['exception_value'] = smart_text(self.exc_value, errors='replace')
  261. if frames:
  262. c['lastframe'] = frames[-1]
  263. return c
  264. def get_traceback_html(self):
  265. "Return HTML version of debug 500 HTTP error page."
  266. t = Template(TECHNICAL_500_TEMPLATE, name='Technical 500 template')
  267. c = Context(self.get_traceback_data())
  268. return t.render(c)
  269. def get_traceback_text(self):
  270. "Return plain text version of debug 500 HTTP error page."
  271. t = Template(TECHNICAL_500_TEXT_TEMPLATE, name='Technical 500 template')
  272. c = Context(self.get_traceback_data(), autoescape=False)
  273. return t.render(c)
  274. def get_template_exception_info(self):
  275. origin, (start, end) = self.exc_value.django_template_source
  276. template_source = origin.reload()
  277. context_lines = 10
  278. line = 0
  279. upto = 0
  280. source_lines = []
  281. before = during = after = ""
  282. for num, next in enumerate(linebreak_iter(template_source)):
  283. if start >= upto and end <= next:
  284. line = num
  285. before = escape(template_source[upto:start])
  286. during = escape(template_source[start:end])
  287. after = escape(template_source[end:next])
  288. source_lines.append( (num, escape(template_source[upto:next])) )
  289. upto = next
  290. total = len(source_lines)
  291. top = max(1, line - context_lines)
  292. bottom = min(total, line + 1 + context_lines)
  293. # In some rare cases, exc_value.args might be empty.
  294. try:
  295. message = self.exc_value.args[0]
  296. except IndexError:
  297. message = '(Could not get exception message)'
  298. self.template_info = {
  299. 'message': message,
  300. 'source_lines': source_lines[top:bottom],
  301. 'before': before,
  302. 'during': during,
  303. 'after': after,
  304. 'top': top,
  305. 'bottom': bottom,
  306. 'total': total,
  307. 'line': line,
  308. 'name': origin.name,
  309. }
  310. def _get_lines_from_file(self, filename, lineno, context_lines, loader=None, module_name=None):
  311. """
  312. Returns context_lines before and after lineno from file.
  313. Returns (pre_context_lineno, pre_context, context_line, post_context).
  314. """
  315. source = None
  316. if loader is not None and hasattr(loader, "get_source"):
  317. source = loader.get_source(module_name)
  318. if source is not None:
  319. source = source.splitlines()
  320. if source is None:
  321. try:
  322. with open(filename, 'rb') as fp:
  323. source = fp.read().splitlines()
  324. except (OSError, IOError):
  325. pass
  326. if source is None:
  327. return None, [], None, []
  328. # If we just read the source from a file, or if the loader did not
  329. # apply tokenize.detect_encoding to decode the source into a Unicode
  330. # string, then we should do that ourselves.
  331. if isinstance(source[0], six.binary_type):
  332. encoding = 'ascii'
  333. for line in source[:2]:
  334. # File coding may be specified. Match pattern from PEP-263
  335. # (http://www.python.org/dev/peps/pep-0263/)
  336. match = re.search(br'coding[:=]\s*([-\w.]+)', line)
  337. if match:
  338. encoding = match.group(1).decode('ascii')
  339. break
  340. source = [six.text_type(sline, encoding, 'replace') for sline in source]
  341. lower_bound = max(0, lineno - context_lines)
  342. upper_bound = lineno + context_lines
  343. pre_context = source[lower_bound:lineno]
  344. context_line = source[lineno]
  345. post_context = source[lineno+1:upper_bound]
  346. return lower_bound, pre_context, context_line, post_context
  347. def get_traceback_frames(self):
  348. frames = []
  349. tb = self.tb
  350. while tb is not None:
  351. # Support for __traceback_hide__ which is used by a few libraries
  352. # to hide internal frames.
  353. if tb.tb_frame.f_locals.get('__traceback_hide__'):
  354. tb = tb.tb_next
  355. continue
  356. filename = tb.tb_frame.f_code.co_filename
  357. function = tb.tb_frame.f_code.co_name
  358. lineno = tb.tb_lineno - 1
  359. loader = tb.tb_frame.f_globals.get('__loader__')
  360. module_name = tb.tb_frame.f_globals.get('__name__') or ''
  361. pre_context_lineno, pre_context, context_line, post_context = self._get_lines_from_file(filename, lineno, 7, loader, module_name)
  362. if pre_context_lineno is not None:
  363. frames.append({
  364. 'tb': tb,
  365. 'type': 'django' if module_name.startswith('django.') else 'user',
  366. 'filename': filename,
  367. 'function': function,
  368. 'lineno': lineno + 1,
  369. 'vars': self.filter.get_traceback_frame_variables(self.request, tb.tb_frame),
  370. 'id': id(tb),
  371. 'pre_context': pre_context,
  372. 'context_line': context_line,
  373. 'post_context': post_context,
  374. 'pre_context_lineno': pre_context_lineno + 1,
  375. })
  376. tb = tb.tb_next
  377. return frames
  378. def format_exception(self):
  379. """
  380. Return the same data as from traceback.format_exception.
  381. """
  382. import traceback
  383. frames = self.get_traceback_frames()
  384. tb = [ (f['filename'], f['lineno'], f['function'], f['context_line']) for f in frames ]
  385. list = ['Traceback (most recent call last):\n']
  386. list += traceback.format_list(tb)
  387. list += traceback.format_exception_only(self.exc_type, self.exc_value)
  388. return list
  389. def technical_404_response(request, exception):
  390. "Create a technical 404 error response. The exception should be the Http404."
  391. try:
  392. tried = exception.args[0]['tried']
  393. except (IndexError, TypeError, KeyError):
  394. tried = []
  395. else:
  396. if (not tried # empty URLconf
  397. or (request.path == '/'
  398. and len(tried) == 1 # default URLconf
  399. and len(tried[0]) == 1
  400. and tried[0][0].app_name == tried[0][0].namespace == 'admin')):
  401. return default_urlconf(request)
  402. urlconf = getattr(request, 'urlconf', settings.ROOT_URLCONF)
  403. if isinstance(urlconf, types.ModuleType):
  404. urlconf = urlconf.__name__
  405. t = Template(TECHNICAL_404_TEMPLATE, name='Technical 404 template')
  406. c = Context({
  407. 'urlconf': urlconf,
  408. 'root_urlconf': settings.ROOT_URLCONF,
  409. 'request_path': request.path_info[1:], # Trim leading slash
  410. 'urlpatterns': tried,
  411. 'reason': force_bytes(exception, errors='replace'),
  412. 'request': request,
  413. 'settings': get_safe_settings(),
  414. })
  415. return HttpResponseNotFound(t.render(c), content_type='text/html')
  416. def default_urlconf(request):
  417. "Create an empty URLconf 404 error response."
  418. t = Template(DEFAULT_URLCONF_TEMPLATE, name='Default URLconf template')
  419. c = Context({})
  420. return HttpResponse(t.render(c), content_type='text/html')
  421. #
  422. # Templates are embedded in the file so that we know the error handler will
  423. # always work even if the template loader is broken.
  424. #
  425. TECHNICAL_500_TEMPLATE = """
  426. <!DOCTYPE html>
  427. <html lang="en">
  428. <head>
  429. <meta http-equiv="content-type" content="text/html; charset=utf-8">
  430. <meta name="robots" content="NONE,NOARCHIVE">
  431. <title>{% if exception_type %}{{ exception_type }}{% else %}Report{% endif %}{% if request %} at {{ request.path_info|escape }}{% endif %}</title>
  432. <style type="text/css">
  433. html * { padding:0; margin:0; }
  434. body * { padding:10px 20px; }
  435. body * * { padding:0; }
  436. body { font:small sans-serif; }
  437. body>div { border-bottom:1px solid #ddd; }
  438. h1 { font-weight:normal; }
  439. h2 { margin-bottom:.8em; }
  440. h2 span { font-size:80%; color:#666; font-weight:normal; }
  441. h3 { margin:1em 0 .5em 0; }
  442. h4 { margin:0 0 .5em 0; font-weight: normal; }
  443. code, pre { font-size: 100%; white-space: pre-wrap; }
  444. table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; }
  445. tbody td, tbody th { vertical-align:top; padding:2px 3px; }
  446. thead th { padding:1px 6px 1px 3px; background:#fefefe; text-align:left; font-weight:normal; font-size:11px; border:1px solid #ddd; }
  447. tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; }
  448. table.vars { margin:5px 0 2px 40px; }
  449. table.vars td, table.req td { font-family:monospace; }
  450. table td.code { width:100%; }
  451. table td.code pre { overflow:hidden; }
  452. table.source th { color:#666; }
  453. table.source td { font-family:monospace; white-space:pre; border-bottom:1px solid #eee; }
  454. ul.traceback { list-style-type:none; color: #222; }
  455. ul.traceback li.frame { padding-bottom:1em; color:#666; }
  456. ul.traceback li.user { background-color:#e0e0e0; color:#000 }
  457. div.context { padding:10px 0; overflow:hidden; }
  458. div.context ol { padding-left:30px; margin:0 10px; list-style-position: inside; }
  459. div.context ol li { font-family:monospace; white-space:pre; color:#777; cursor:pointer; }
  460. div.context ol li pre { display:inline; }
  461. div.context ol.context-line li { color:#505050; background-color:#dfdfdf; }
  462. div.context ol.context-line li span { position:absolute; right:32px; }
  463. .user div.context ol.context-line li { background-color:#bbb; color:#000; }
  464. .user div.context ol li { color:#666; }
  465. div.commands { margin-left: 40px; }
  466. div.commands a { color:#555; text-decoration:none; }
  467. .user div.commands a { color: black; }
  468. #summary { background: #ffc; }
  469. #summary h2 { font-weight: normal; color: #666; }
  470. #explanation { background:#eee; }
  471. #template, #template-not-exist { background:#f6f6f6; }
  472. #template-not-exist ul { margin: 0 0 0 20px; }
  473. #unicode-hint { background:#eee; }
  474. #traceback { background:#eee; }
  475. #requestinfo { background:#f6f6f6; padding-left:120px; }
  476. #summary table { border:none; background:transparent; }
  477. #requestinfo h2, #requestinfo h3 { position:relative; margin-left:-100px; }
  478. #requestinfo h3 { margin-bottom:-1em; }
  479. .error { background: #ffc; }
  480. .specific { color:#cc3300; font-weight:bold; }
  481. h2 span.commands { font-size:.7em;}
  482. span.commands a:link {color:#5E5694;}
  483. pre.exception_value { font-family: sans-serif; color: #666; font-size: 1.5em; margin: 10px 0 10px 0; }
  484. </style>
  485. {% if not is_email %}
  486. <script type="text/javascript">
  487. //<!--
  488. function getElementsByClassName(oElm, strTagName, strClassName){
  489. // Written by Jonathan Snook, http://www.snook.ca/jon; Add-ons by Robert Nyman, http://www.robertnyman.com
  490. var arrElements = (strTagName == "*" && document.all)? document.all :
  491. oElm.getElementsByTagName(strTagName);
  492. var arrReturnElements = new Array();
  493. strClassName = strClassName.replace(/\-/g, "\\-");
  494. var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
  495. var oElement;
  496. for(var i=0; i<arrElements.length; i++){
  497. oElement = arrElements[i];
  498. if(oRegExp.test(oElement.className)){
  499. arrReturnElements.push(oElement);
  500. }
  501. }
  502. return (arrReturnElements)
  503. }
  504. function hideAll(elems) {
  505. for (var e = 0; e < elems.length; e++) {
  506. elems[e].style.display = 'none';
  507. }
  508. }
  509. window.onload = function() {
  510. hideAll(getElementsByClassName(document, 'table', 'vars'));
  511. hideAll(getElementsByClassName(document, 'ol', 'pre-context'));
  512. hideAll(getElementsByClassName(document, 'ol', 'post-context'));
  513. hideAll(getElementsByClassName(document, 'div', 'pastebin'));
  514. }
  515. function toggle() {
  516. for (var i = 0; i < arguments.length; i++) {
  517. var e = document.getElementById(arguments[i]);
  518. if (e) {
  519. e.style.display = e.style.display == 'none' ? 'block' : 'none';
  520. }
  521. }
  522. return false;
  523. }
  524. function varToggle(link, id) {
  525. toggle('v' + id);
  526. var s = link.getElementsByTagName('span')[0];
  527. var uarr = String.fromCharCode(0x25b6);
  528. var darr = String.fromCharCode(0x25bc);
  529. s.innerHTML = s.innerHTML == uarr ? darr : uarr;
  530. return false;
  531. }
  532. function switchPastebinFriendly(link) {
  533. s1 = "Switch to copy-and-paste view";
  534. s2 = "Switch back to interactive view";
  535. link.innerHTML = link.innerHTML == s1 ? s2 : s1;
  536. toggle('browserTraceback', 'pastebinTraceback');
  537. return false;
  538. }
  539. //-->
  540. </script>
  541. {% endif %}
  542. </head>
  543. <body>
  544. <div id="summary">
  545. <h1>{% if exception_type %}{{ exception_type }}{% else %}Report{% endif %}{% if request %} at {{ request.path_info|escape }}{% endif %}</h1>
  546. <pre class="exception_value">{% if exception_value %}{{ exception_value|force_escape }}{% else %}No exception message supplied{% endif %}</pre>
  547. <table class="meta">
  548. {% if request %}
  549. <tr>
  550. <th>Request Method:</th>
  551. <td>{{ request.META.REQUEST_METHOD }}</td>
  552. </tr>
  553. <tr>
  554. <th>Request URL:</th>
  555. <td>{{ request.build_absolute_uri|escape }}</td>
  556. </tr>
  557. {% endif %}
  558. <tr>
  559. <th>Django Version:</th>
  560. <td>{{ django_version_info }}</td>
  561. </tr>
  562. {% if exception_type %}
  563. <tr>
  564. <th>Exception Type:</th>
  565. <td>{{ exception_type }}</td>
  566. </tr>
  567. {% endif %}
  568. {% if exception_type and exception_value %}
  569. <tr>
  570. <th>Exception Value:</th>
  571. <td><pre>{{ exception_value|force_escape }}</pre></td>
  572. </tr>
  573. {% endif %}
  574. {% if lastframe %}
  575. <tr>
  576. <th>Exception Location:</th>
  577. <td>{{ lastframe.filename|escape }} in {{ lastframe.function|escape }}, line {{ lastframe.lineno }}</td>
  578. </tr>
  579. {% endif %}
  580. <tr>
  581. <th>Python Executable:</th>
  582. <td>{{ sys_executable|escape }}</td>
  583. </tr>
  584. <tr>
  585. <th>Python Version:</th>
  586. <td>{{ sys_version_info }}</td>
  587. </tr>
  588. <tr>
  589. <th>Python Path:</th>
  590. <td><pre>{{ sys_path|pprint }}</pre></td>
  591. </tr>
  592. <tr>
  593. <th>Server time:</th>
  594. <td>{{server_time|date:"r"}}</td>
  595. </tr>
  596. </table>
  597. </div>
  598. {% if unicode_hint %}
  599. <div id="unicode-hint">
  600. <h2>Unicode error hint</h2>
  601. <p>The string that could not be encoded/decoded was: <strong>{{ unicode_hint|force_escape }}</strong></p>
  602. </div>
  603. {% endif %}
  604. {% if template_does_not_exist %}
  605. <div id="template-not-exist">
  606. <h2>Template-loader postmortem</h2>
  607. {% if loader_debug_info %}
  608. <p>Django tried loading these templates, in this order:</p>
  609. <ul>
  610. {% for loader in loader_debug_info %}
  611. <li>Using loader <code>{{ loader.loader }}</code>:
  612. <ul>
  613. {% for t in loader.templates %}<li><code>{{ t.name }}</code> ({{ t.status }})</li>{% endfor %}
  614. </ul>
  615. </li>
  616. {% endfor %}
  617. </ul>
  618. {% else %}
  619. <p>Django couldn't find any templates because your <code>TEMPLATE_LOADERS</code> setting is empty!</p>
  620. {% endif %}
  621. </div>
  622. {% endif %}
  623. {% if template_info %}
  624. <div id="template">
  625. <h2>Error during template rendering</h2>
  626. <p>In template <code>{{ template_info.name }}</code>, error at line <strong>{{ template_info.line }}</strong></p>
  627. <h3>{{ template_info.message }}</h3>
  628. <table class="source{% if template_info.top %} cut-top{% endif %}{% ifnotequal template_info.bottom template_info.total %} cut-bottom{% endifnotequal %}">
  629. {% for source_line in template_info.source_lines %}
  630. {% ifequal source_line.0 template_info.line %}
  631. <tr class="error"><th>{{ source_line.0 }}</th>
  632. <td>{{ template_info.before }}<span class="specific">{{ template_info.during }}</span>{{ template_info.after }}</td></tr>
  633. {% else %}
  634. <tr><th>{{ source_line.0 }}</th>
  635. <td>{{ source_line.1 }}</td></tr>
  636. {% endifequal %}
  637. {% endfor %}
  638. </table>
  639. </div>
  640. {% endif %}
  641. {% if frames %}
  642. <div id="traceback">
  643. <h2>Traceback <span class="commands">{% if not is_email %}<a href="#" onclick="return switchPastebinFriendly(this);">Switch to copy-and-paste view</a></span>{% endif %}</h2>
  644. {% autoescape off %}
  645. <div id="browserTraceback">
  646. <ul class="traceback">
  647. {% for frame in frames %}
  648. <li class="frame {{ frame.type }}">
  649. <code>{{ frame.filename|escape }}</code> in <code>{{ frame.function|escape }}</code>
  650. {% if frame.context_line %}
  651. <div class="context" id="c{{ frame.id }}">
  652. {% if frame.pre_context and not is_email %}
  653. <ol start="{{ frame.pre_context_lineno }}" class="pre-context" id="pre{{ frame.id }}">{% for line in frame.pre_context %}<li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')"><pre>{{ line|escape }}</pre></li>{% endfor %}</ol>
  654. {% endif %}
  655. <ol start="{{ frame.lineno }}" class="context-line"><li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')"><pre>{{ frame.context_line|escape }}</pre>{% if not is_email %} <span>...</span>{% endif %}</li></ol>
  656. {% if frame.post_context and not is_email %}
  657. <ol start='{{ frame.lineno|add:"1" }}' class="post-context" id="post{{ frame.id }}">{% for line in frame.post_context %}<li onclick="toggle('pre{{ frame.id }}', 'post{{ frame.id }}')"><pre>{{ line|escape }}</pre></li>{% endfor %}</ol>
  658. {% endif %}
  659. </div>
  660. {% endif %}
  661. {% if frame.vars %}
  662. <div class="commands">
  663. {% if is_email %}
  664. <h2>Local Vars</h2>
  665. {% else %}
  666. <a href="#" onclick="return varToggle(this, '{{ frame.id }}')"><span>&#x25b6;</span> Local vars</a>
  667. {% endif %}
  668. </div>
  669. <table class="vars" id="v{{ frame.id }}">
  670. <thead>
  671. <tr>
  672. <th>Variable</th>
  673. <th>Value</th>
  674. </tr>
  675. </thead>
  676. <tbody>
  677. {% for var in frame.vars|dictsort:"0" %}
  678. <tr>
  679. <td>{{ var.0|force_escape }}</td>
  680. <td class="code"><pre>{{ var.1 }}</pre></td>
  681. </tr>
  682. {% endfor %}
  683. </tbody>
  684. </table>
  685. {% endif %}
  686. </li>
  687. {% endfor %}
  688. </ul>
  689. </div>
  690. {% endautoescape %}
  691. <form action="http://dpaste.com/" name="pasteform" id="pasteform" method="post">
  692. {% if not is_email %}
  693. <div id="pastebinTraceback" class="pastebin">
  694. <input type="hidden" name="language" value="PythonConsole">
  695. <input type="hidden" name="title" value="{{ exception_type|escape }}{% if request %} at {{ request.path_info|escape }}{% endif %}">
  696. <input type="hidden" name="source" value="Django Dpaste Agent">
  697. <input type="hidden" name="poster" value="Django">
  698. <textarea name="content" id="traceback_area" cols="140" rows="25">
  699. Environment:
  700. {% if request %}
  701. Request Method: {{ request.META.REQUEST_METHOD }}
  702. Request URL: {{ request.build_absolute_uri|escape }}
  703. {% endif %}
  704. Django Version: {{ django_version_info }}
  705. Python Version: {{ sys_version_info }}
  706. Installed Applications:
  707. {{ settings.INSTALLED_APPS|pprint }}
  708. Installed Middleware:
  709. {{ settings.MIDDLEWARE_CLASSES|pprint }}
  710. {% if template_does_not_exist %}Template Loader Error:
  711. {% if loader_debug_info %}Django tried loading these templates, in this order:
  712. {% for loader in loader_debug_info %}Using loader {{ loader.loader }}:
  713. {% for t in loader.templates %}{{ t.name }} ({{ t.status }})
  714. {% endfor %}{% endfor %}
  715. {% else %}Django couldn't find any templates because your TEMPLATE_LOADERS setting is empty!
  716. {% endif %}
  717. {% endif %}{% if template_info %}
  718. Template error:
  719. In template {{ template_info.name }}, error at line {{ template_info.line }}
  720. {{ template_info.message }}{% for source_line in template_info.source_lines %}{% ifequal source_line.0 template_info.line %}
  721. {{ source_line.0 }} : {{ template_info.before }} {{ template_info.during }} {{ template_info.after }}
  722. {% else %}
  723. {{ source_line.0 }} : {{ source_line.1 }}
  724. {% endifequal %}{% endfor %}{% endif %}
  725. Traceback:
  726. {% for frame in frames %}File "{{ frame.filename|escape }}" in {{ frame.function|escape }}
  727. {% if frame.context_line %} {{ frame.lineno }}. {{ frame.context_line|escape }}{% endif %}
  728. {% endfor %}
  729. Exception Type: {{ exception_type|escape }}{% if request %} at {{ request.path_info|escape }}{% endif %}
  730. Exception Value: {{ exception_value|force_escape }}
  731. </textarea>
  732. <br><br>
  733. <input type="submit" value="Share this traceback on a public Web site">
  734. </div>
  735. </form>
  736. </div>
  737. {% endif %}
  738. {% endif %}
  739. <div id="requestinfo">
  740. <h2>Request information</h2>
  741. {% if request %}
  742. <h3 id="get-info">GET</h3>
  743. {% if request.GET %}
  744. <table class="req">
  745. <thead>
  746. <tr>
  747. <th>Variable</th>
  748. <th>Value</th>
  749. </tr>
  750. </thead>
  751. <tbody>
  752. {% for var in request.GET.items %}
  753. <tr>
  754. <td>{{ var.0 }}</td>
  755. <td class="code"><pre>{{ var.1|pprint }}</pre></td>
  756. </tr>
  757. {% endfor %}
  758. </tbody>
  759. </table>
  760. {% else %}
  761. <p>No GET data</p>
  762. {% endif %}
  763. <h3 id="post-info">POST</h3>
  764. {% if filtered_POST %}
  765. <table class="req">
  766. <thead>
  767. <tr>
  768. <th>Variable</th>
  769. <th>Value</th>
  770. </tr>
  771. </thead>
  772. <tbody>
  773. {% for var in filtered_POST.items %}
  774. <tr>
  775. <td>{{ var.0 }}</td>
  776. <td class="code"><pre>{{ var.1|pprint }}</pre></td>
  777. </tr>
  778. {% endfor %}
  779. </tbody>
  780. </table>
  781. {% else %}
  782. <p>No POST data</p>
  783. {% endif %}
  784. <h3 id="files-info">FILES</h3>
  785. {% if request.FILES %}
  786. <table class="req">
  787. <thead>
  788. <tr>
  789. <th>Variable</th>
  790. <th>Value</th>
  791. </tr>
  792. </thead>
  793. <tbody>
  794. {% for var in request.FILES.items %}
  795. <tr>
  796. <td>{{ var.0 }}</td>
  797. <td class="code"><pre>{{ var.1|pprint }}</pre></td>
  798. </tr>
  799. {% endfor %}
  800. </tbody>
  801. </table>
  802. {% else %}
  803. <p>No FILES data</p>
  804. {% endif %}
  805. <h3 id="cookie-info">COOKIES</h3>
  806. {% if request.COOKIES %}
  807. <table class="req">
  808. <thead>
  809. <tr>
  810. <th>Variable</th>
  811. <th>Value</th>
  812. </tr>
  813. </thead>
  814. <tbody>
  815. {% for var in request.COOKIES.items %}
  816. <tr>
  817. <td>{{ var.0 }}</td>
  818. <td class="code"><pre>{{ var.1|pprint }}</pre></td>
  819. </tr>
  820. {% endfor %}
  821. </tbody>
  822. </table>
  823. {% else %}
  824. <p>No cookie data</p>
  825. {% endif %}
  826. <h3 id="meta-info">META</h3>
  827. <table class="req">
  828. <thead>
  829. <tr>
  830. <th>Variable</th>
  831. <th>Value</th>
  832. </tr>
  833. </thead>
  834. <tbody>
  835. {% for var in request.META.items|dictsort:"0" %}
  836. <tr>
  837. <td>{{ var.0 }}</td>
  838. <td class="code"><pre>{{ var.1|pprint }}</pre></td>
  839. </tr>
  840. {% endfor %}
  841. </tbody>
  842. </table>
  843. {% else %}
  844. <p>Request data not supplied</p>
  845. {% endif %}
  846. <h3 id="settings-info">Settings</h3>
  847. <h4>Using settings module <code>{{ settings.SETTINGS_MODULE }}</code></h4>
  848. <table class="req">
  849. <thead>
  850. <tr>
  851. <th>Setting</th>
  852. <th>Value</th>
  853. </tr>
  854. </thead>
  855. <tbody>
  856. {% for var in settings.items|dictsort:"0" %}
  857. <tr>
  858. <td>{{ var.0 }}</td>
  859. <td class="code"><pre>{{ var.1|pprint }}</pre></td>
  860. </tr>
  861. {% endfor %}
  862. </tbody>
  863. </table>
  864. </div>
  865. {% if not is_email %}
  866. <div id="explanation">
  867. <p>
  868. You're seeing this error because you have <code>DEBUG = True</code> in your
  869. Django settings file. Change that to <code>False</code>, and Django will
  870. display a standard 500 page.
  871. </p>
  872. </div>
  873. {% endif %}
  874. </body>
  875. </html>
  876. """
  877. TECHNICAL_500_TEXT_TEMPLATE = """{% load firstof from future %}{% firstof exception_type 'Report' %}{% if request %} at {{ request.path_info }}{% endif %}
  878. {% firstof exception_value 'No exception message supplied' %}
  879. {% if request %}
  880. Request Method: {{ request.META.REQUEST_METHOD }}
  881. Request URL: {{ request.build_absolute_uri }}{% endif %}
  882. Django Version: {{ django_version_info }}
  883. Python Executable: {{ sys_executable }}
  884. Python Version: {{ sys_version_info }}
  885. Python Path: {{ sys_path }}
  886. Server time: {{server_time|date:"r"}}
  887. Installed Applications:
  888. {{ settings.INSTALLED_APPS|pprint }}
  889. Installed Middleware:
  890. {{ settings.MIDDLEWARE_CLASSES|pprint }}
  891. {% if template_does_not_exist %}Template loader Error:
  892. {% if loader_debug_info %}Django tried loading these templates, in this order:
  893. {% for loader in loader_debug_info %}Using loader {{ loader.loader }}:
  894. {% for t in loader.templates %}{{ t.name }} ({{ t.status }})
  895. {% endfor %}{% endfor %}
  896. {% else %}Django couldn't find any templates because your TEMPLATE_LOADERS setting is empty!
  897. {% endif %}
  898. {% endif %}{% if template_info %}
  899. Template error:
  900. In template {{ template_info.name }}, error at line {{ template_info.line }}
  901. {{ template_info.message }}{% for source_line in template_info.source_lines %}{% ifequal source_line.0 template_info.line %}
  902. {{ source_line.0 }} : {{ template_info.before }} {{ template_info.during }} {{ template_info.after }}
  903. {% else %}
  904. {{ source_line.0 }} : {{ source_line.1 }}
  905. {% endifequal %}{% endfor %}{% endif %}{% if frames %}
  906. Traceback:
  907. {% for frame in frames %}File "{{ frame.filename }}" in {{ frame.function }}
  908. {% if frame.context_line %} {{ frame.lineno }}. {{ frame.context_line }}{% endif %}
  909. {% endfor %}
  910. {% if exception_type %}Exception Type: {{ exception_type }}{% if request %} at {{ request.path_info }}{% endif %}
  911. {% if exception_value %}Exception Value: {{ exception_value }}{% endif %}{% endif %}{% endif %}
  912. {% if request %}Request information:
  913. GET:{% for k, v in request.GET.items %}
  914. {{ k }} = {{ v|stringformat:"r" }}{% empty %} No GET data{% endfor %}
  915. POST:{% for k, v in filtered_POST.items %}
  916. {{ k }} = {{ v|stringformat:"r" }}{% empty %} No POST data{% endfor %}
  917. FILES:{% for k, v in request.FILES.items %}
  918. {{ k }} = {{ v|stringformat:"r" }}{% empty %} No FILES data{% endfor %}
  919. COOKIES:{% for k, v in request.COOKIES.items %}
  920. {{ k }} = {{ v|stringformat:"r" }}{% empty %} No cookie data{% endfor %}
  921. META:{% for k, v in request.META.items|dictsort:"0" %}
  922. {{ k }} = {{ v|stringformat:"r" }}{% endfor %}
  923. {% else %}Request data not supplied
  924. {% endif %}
  925. Settings:
  926. Using settings module {{ settings.SETTINGS_MODULE }}{% for k, v in settings.items|dictsort:"0" %}
  927. {{ k }} = {{ v|stringformat:"r" }}{% endfor %}
  928. You're seeing this error because you have DEBUG = True in your
  929. Django settings file. Change that to False, and Django will
  930. display a standard 500 page.
  931. """
  932. TECHNICAL_404_TEMPLATE = """
  933. <!DOCTYPE html>
  934. <html lang="en">
  935. <head>
  936. <meta http-equiv="content-type" content="text/html; charset=utf-8">
  937. <title>Page not found at {{ request.path_info|escape }}</title>
  938. <meta name="robots" content="NONE,NOARCHIVE">
  939. <style type="text/css">
  940. html * { padding:0; margin:0; }
  941. body * { padding:10px 20px; }
  942. body * * { padding:0; }
  943. body { font:small sans-serif; background:#eee; }
  944. body>div { border-bottom:1px solid #ddd; }
  945. h1 { font-weight:normal; margin-bottom:.4em; }
  946. h1 span { font-size:60%; color:#666; font-weight:normal; }
  947. table { border:none; border-collapse: collapse; width:100%; }
  948. td, th { vertical-align:top; padding:2px 3px; }
  949. th { width:12em; text-align:right; color:#666; padding-right:.5em; }
  950. #info { background:#f6f6f6; }
  951. #info ol { margin: 0.5em 4em; }
  952. #info ol li { font-family: monospace; }
  953. #summary { background: #ffc; }
  954. #explanation { background:#eee; border-bottom: 0px none; }
  955. </style>
  956. </head>
  957. <body>
  958. <div id="summary">
  959. <h1>Page not found <span>(404)</span></h1>
  960. <table class="meta">
  961. <tr>
  962. <th>Request Method:</th>
  963. <td>{{ request.META.REQUEST_METHOD }}</td>
  964. </tr>
  965. <tr>
  966. <th>Request URL:</th>
  967. <td>{{ request.build_absolute_uri|escape }}</td>
  968. </tr>
  969. </table>
  970. </div>
  971. <div id="info">
  972. {% if urlpatterns %}
  973. <p>
  974. Using the URLconf defined in <code>{{ urlconf }}</code>,
  975. Django tried these URL patterns, in this order:
  976. </p>
  977. <ol>
  978. {% for pattern in urlpatterns %}
  979. <li>
  980. {% for pat in pattern %}
  981. {{ pat.regex.pattern }}
  982. {% if forloop.last and pat.name %}[name='{{ pat.name }}']{% endif %}
  983. {% endfor %}
  984. </li>
  985. {% endfor %}
  986. </ol>
  987. <p>The current URL, <code>{{ request_path|escape }}</code>, didn't match any of these.</p>
  988. {% else %}
  989. <p>{{ reason }}</p>
  990. {% endif %}
  991. </div>
  992. <div id="explanation">
  993. <p>
  994. You're seeing this error because you have <code>DEBUG = True</code> in
  995. your Django settings file. Change that to <code>False</code>, and Django
  996. will display a standard 404 page.
  997. </p>
  998. </div>
  999. </body>
  1000. </html>
  1001. """
  1002. DEFAULT_URLCONF_TEMPLATE = """
  1003. <!DOCTYPE html>
  1004. <html lang="en"><head>
  1005. <meta http-equiv="content-type" content="text/html; charset=utf-8">
  1006. <meta name="robots" content="NONE,NOARCHIVE"><title>Welcome to Django</title>
  1007. <style type="text/css">
  1008. html * { padding:0; margin:0; }
  1009. body * { padding:10px 20px; }
  1010. body * * { padding:0; }
  1011. body { font:small sans-serif; }
  1012. body>div { border-bottom:1px solid #ddd; }
  1013. h1 { font-weight:normal; }
  1014. h2 { margin-bottom:.8em; }
  1015. h2 span { font-size:80%; color:#666; font-weight:normal; }
  1016. h3 { margin:1em 0 .5em 0; }
  1017. h4 { margin:0 0 .5em 0; font-weight: normal; }
  1018. table { border:1px solid #ccc; border-collapse: collapse; width:100%; background:white; }
  1019. tbody td, tbody th { vertical-align:top; padding:2px 3px; }
  1020. thead th { padding:1px 6px 1px 3px; background:#fefefe; text-align:left; font-weight:normal; font-size:11px; border:1px solid #ddd; }
  1021. tbody th { width:12em; text-align:right; color:#666; padding-right:.5em; }
  1022. #summary { background: #e0ebff; }
  1023. #summary h2 { font-weight: normal; color: #666; }
  1024. #explanation { background:#eee; }
  1025. #instructions { background:#f6f6f6; }
  1026. #summary table { border:none; background:transparent; }
  1027. </style>
  1028. </head>
  1029. <body>
  1030. <div id="summary">
  1031. <h1>It worked!</h1>
  1032. <h2>Congratulations on your first Django-powered page.</h2>
  1033. </div>
  1034. <div id="instructions">
  1035. <p>
  1036. Of course, you haven't actually done any work yet.
  1037. Next, start your first app by running <code>python manage.py startapp [appname]</code>.
  1038. </p>
  1039. </div>
  1040. <div id="explanation">
  1041. <p>
  1042. You're seeing this message because you have <code>DEBUG = True</code> in your
  1043. Django settings file and you haven't configured any URLs. Get to work!
  1044. </p>
  1045. </div>
  1046. </body></html>
  1047. """