Django class-based views: Invoking (forwarding to) a different class-based view

Question:

With Django functional views, it is very simple to invoke a different view function in order to “forward” a request to a different view. (The django codebase sometimes does this in its admin views.) You simply call the function and return the result.

for example:

def change_view(request, *args, **kwargs):
  if 'save_as_new' in request.GET:
    return add_view(request, *args, **kwargs)

Its also easy enough to forward from a functional view to a Class-based view:

def change_view(request, *args, **kwargs):
  if 'save_as_new' in request.GET:
    return AddView.as_view()(request, *args, **kwargs)

However, I’m confused as to the proper or best way to conditionally invoke or forward to a second class-based view from a first class-based view, based on the existence or value of a url (GET) param or, alternatively, on the value of one of the args or kwargs from the url conf. Note that I’m not at all interested in doing a redirect here.

Asked By: B Robster

||

Answers:

class CBViewA(View):
    def get(self, request, *args, **kwargs):
        if 'save_as_new' in request.GET:
            return AddView.as_view()(request, *args, **kwargs)

django run another class-based view (CBV) in a CBV?

Answered By: ndpu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.