Search code examples
djangodjango-templatesdjango-sekizai

Django view not updating context properly


So I have a custom template tag, which is rather simple. It takes a view name, renders it, and returns its content. The problem is, while using .as_view() on them gets me the content, it doesn't seem to properly set the context, because django-sekizai's addtoblocks do not properly add to main template. On the other hand, if I instance the view directly and call .render_to_response(context).render() on it, the context will update and sekizai will inject block data into base template. However, this second approach will not correctly render forms (which .as_view() does). Is there a way to do this without dirtily calling both?

class PopupNode(template.base.Node):
    def __init__(self, popup):
        self.popup = popup

    def render(self, context):
        # only needed to update context
        view_object = self.popup()
        view_object.request = context['request']
        view_object.render_to_response(context).render()

        # actual content
        view_function = self.popup.as_view()
        template_response = view_function(context['request'], context=context)
        template_response.render()
        return template_response.content

Solution

  • As it turns out, the inherited get() function disregards any pre-existing context and renders its own (which is logical, since views do not expect to be rendered within other views), thus not letting sekizai update it. calling .render_to_template() directly allows you to supply the context, so it works. Overriding the get() method to accept prior context and inject its own worked.