Sunday, May 29, 2011

Re: Dynamic template loader with TemplateResponse

Here is the solution I settled on for now. This is obviously not
optimally efficient because I have to hit the filesystem twice for
every page load. Does anyone know of a way to raise Http404 during
template rendering? I tried it with a TemplateResponse subclass but
ran into some problems with _is_rendered. I can't think of a way to
handle a 404 at the template rendering stage.

from django.http import Http404
from django.template import TemplateDoesNotExist
from django.template.loader import get_template
from django.views.generic import TemplateView

class ContentView(TemplateView):
def get_template_names(self):
return [self.kwargs['template_name']]

def render_to_response(self, context, **response_kwargs):
try:
get_template(self.get_template_names()[0])
except TemplateDoesNotExist:
raise Http404

return super(ContentView, self).render_to_response(context,
**response_kwargs)

On May 23, 3:01 pm, Brian Morton <rokclim...@gmail.com> wrote:
> I have some legacy code that I used to dynamically load a template based on
> url if it exists and render a 404 if it doesn't exist.
>
> def content(request, template_name='index'):
>     try:
>         return direct_to_template(request, '%s.html' % template_name)
>     except TemplateDoesNotExist:
>         raise Http404
>
> I'm having difficulty conceptualizing how to do this in trunk (1.4) with
> TemplateResponse.  Since everything happens inside response.render() outside
> of the view, I do not have that level of control at this stage.
>
> Should I extend BaseLoader to load the 404 template instead of raising an
> exception if it is not found?  Or should I extend SimpleTemplateResponse to
> do something similar?  Or is there a better way to do this?

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment