Can I raise Http404 in a Django template tag?
I have a Django application 开发者_JS百科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?
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.
If the page is User specific, you should get the user to @login_required
before rendering that page, so that you know that the user exists.
Otherwise, by convention, you should just fail silently in the template tags.
What you should do is check within your template if the user
variable exists before displaying the profile
tag.
I can see two ways:
Use if statement with javascript code to redirect, like
{% if profile_not_exist %}
Javascript with redirect
{% else %}
Generic code
{% endif %}
Or define logic in view( better way ), like
def index(request):
if(profile_not_exist):
indexTemplate = loader.get_template('404.html')
else:
indexTemplate = loader.get_template('index.html')
精彩评论