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.

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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?
@TimSaylor From the docs, 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)
@TimSaylor In particular, rendering happens here: github.com/django/django/blob/master/django/core/handlers/…
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.