Search code examples
djangodjango-templatesdjango-custom-tags

Django: Should custom template simple tags raise exception or fail silently?


I have tried to find answer to this question from the official docs, but all that I could find is:

render() should never raise TemplateSyntaxError or any other exception. It should fail silently, just as template filters should

But the above doesn't really answer the question and, perhaps, has confused me even more, because it applies to regular custom tags, and my concern is with simple tags.

Here is an example (and the question itself):

@register.simple_tag
def foo(formfield):
    if isinstance(formfield, forms.ChoiceField):
      # do something
    else:
      # This function doesn't deal with non-ChoiceField. 
      # Should it raise exception or fail silently?

If your answer is to raise exception, would it be TemplateSyntaxError or other exception?


Solution

  • I think the answer is that "it depends on what's right for your app". If you need or want to code defensively, raise an exception. If there's a valid business reason to raise an exception because something won't get displayed, like a price or something, then raise an exception, or at least a Warning.

    Otherwise, just let it do nothing and be happy that you're not looking at a .NET MVC stack trace :)