Search code examples
djangohttp-status-code-404templatetags

Can I raise Http404 in a Django template tag?


I have a Django application that provides template tag profile. The tag accepts a username as its argument. How should I treat the situation when there exists no User instance with the given username? Does it make sense to raise HTTP 404 inside a template tag? Or should I simply pass an empty dictionary to the template?


Solution

  • I don't think it's possible to raise a 404 from the template, and you shouldn't do it if you could. You should keep the logic and presentation separate.

    You have two sound possibilities.

    • Don't render anything with your template tag (fail silently)
    • Raise a template error.

    You don't say exactly what your template tag is doing, so I can't recommend any of the two, but the most normal thing to do with a template tag, is to fail silently.