23

I'm currently trying to call a class based Generic view from within another class based generic view and cant seem to do it correctly.

Ways I've tried:

result = CategoryTypes.as_view()  # The same way you put it in the urlconf
print result

Prints: <function CategoryTypes at 0x92bd924>

CategoryTypes.as_view()(self.request)
# &
CategoryTypes().dispatch(self.request)

Tracebacks:

ContentNotRenderedError at /crm/categories/company/ The response content must be rendered before it can be accessed.

result = CategoryTypes().__init__()
print result

Prints: None

How do I call this from another view? I've seriously tried every method in the class and way of calling it I can think of.

Montaro
  • 9,240
  • 6
  • 29
  • 30
Joshua Jonah
  • 278
  • 1
  • 2
  • 6

2 Answers2

43

The first way -- CategoryTypes.as_view()(self.request) -- is right. The problem is that if your view returns a TemplateResponse, its render method isn't called automatically.

So if you need to access the content of the response, call render() on it first.

Ismail Badawi
  • 36,054
  • 7
  • 85
  • 97
  • This is the exact behavior I'm seeing. I don't call render on the response object when the view is called from the web server, so what's the difference when calling it manually that makes it necessary? – Tim Saylor Sep 10 '13 at 04:34
  • @TimSaylor From [the docs](https://docs.djangoproject.com/en/dev/ref/template-response/), `TemplateResponse` is meant to allow decorators and middleware to modify the response before it's rendered (e.g. changing the template and context), so it's not rendered until later (details [here](https://docs.djangoproject.com/en/dev/ref/template-response/#the-rendering-process)) – Ismail Badawi Sep 10 '13 at 15:52
  • @TimSaylor In particular, rendering happens here: https://github.com/django/django/blob/master/django/core/handlers/base.py#L134-139 – Ismail Badawi Sep 10 '13 at 16:03
1

Or you can directly access just content via result.rendered_content. Before making this be sure you will set session into your request before passing into a view:

self.request.session = {}
CategoryTypes.as_view()(self.request)
Fusion
  • 5,046
  • 5
  • 42
  • 51