Skip to content

Instantly share code, notes, and snippets.

@kezabelle
Last active March 6, 2019 16:02
Show Gist options
  • Save kezabelle/fa12e90a576a000b888f63ce872e8ce3 to your computer and use it in GitHub Desktop.
Save kezabelle/fa12e90a576a000b888f63ce872e8ce3 to your computer and use it in GitHub Desktop.
Make Django templates error super loudly, maybe?
from django.template import TemplateSyntaxError
from django.template.base import Variable, VariableDoesNotExist
old_resolve = Variable._resolve_lookup
def x(self, context):
try:
return old_resolve(self, context)
except VariableDoesNotExist as e:
part = e.params[0]
if part not in ("SETTINGS_MODULE",):
# I dunno. I think because I'm using a UserSettingsHolder and not
# an actual Settings, failing to check this caused the
# technical 500 page to fail to render ... lol.
if part != self.var:
msg = u"Token '{token}' of '{var}' does not resolve"
else:
msg = u"Variable '{token}' does not exist"
raise TemplateSyntaxError(msg.format(token=part, var=self.var))
# this functions the same as string_if_invalid I guess.
# It is only hit for SETTINGS_MODULE
return "<MISSING>"
Variable._resolve_lookup = x
@kezabelle
Copy link
Author

Alternatively if you just wanted variables to complain loudly, and not attribute access inside nodes like {% if ... %}


class Oof(object):
    def __mod__(self, other):
        raise LookupError("Invalid value for %s" % (other,))

    def __contains__(self, item):
        return item == '%s'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment