Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions django/template/loader_tags.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,13 @@ def construct_relative_path(
# relative path.
return relative_name

if current_template_name is None:
# Unknown origin (e.g. Template('...').render(Context({...})).
raise TemplateSyntaxError(
f"The relative path {relative_name} cannot be evaluated due to "
"an unknown template origin."
)

new_name = posixpath.normpath(
posixpath.join(
posixpath.dirname(current_template_name.lstrip("/")),
Expand Down
13 changes: 12 additions & 1 deletion tests/template_tests/syntax_tests/test_exceptions.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from django.template import TemplateDoesNotExist, TemplateSyntaxError
from django.template import Template, TemplateDoesNotExist, TemplateSyntaxError
from django.test import SimpleTestCase

from ..utils import setup
Expand Down Expand Up @@ -64,3 +64,14 @@ def test_exception05(self):
"""
with self.assertRaises(TemplateSyntaxError):
self.engine.render_to_string("exception05")

def test_unknown_origin_relative_path(self):
files = ["./nonexistent.html", "../nonexistent.html"]
for template_name in files:
with self.subTest(template_name=template_name):
msg = (
f"The relative path '{template_name}' cannot be evaluated due to "
"an unknown template origin."
)
with self.assertRaisesMessage(TemplateSyntaxError, msg):
Template(f"{{% extends '{template_name}' %}}")