Controller Class for Views

April 18, 2013
Not specified
urls views
0 (after 0 ratings)

I wanted to be able to share common code among a subset of views without copy-and-pasting the code or the same function into each view, so I decided to wrap a class around the views so that the common code (i.e. loading a model that each of the views would affect) can go in the init of that class. I created the controller_view function above to allow the urls to access those class methods. It would be called something like this:

url(r'^someview$', controller_view(SomeController, 'someview'), name='someview'),

Where the SomeController inherits (or is structured like) the Controller class above and implements init and someview as methods.

I'm new to Django so it's entirely possible I've missed something that already does this or that makes this unnecessary. If so, let me know so that I can figure out how to do this right, otherwise, hopefully this is helpful to someone else out there.

def controller_view(controller, view):
    def as_view(request, *args, **kwargs):
        return getattr(controller(request, *args, **kwargs), view)(*args, **kwargs)
    return as_view

class Controller:
    def __init__(self, request, *args, **kwargs):
        self.request = request

More like this


justhamade (on April 22, 2013):
<p>I think you reimplemented classes based views. </p>


justhamade (on April 22, 2013):
<p>Correction. Classed based views. </p>


jovialbard (on April 22, 2013):
<p>Hmm, if I did then the documentation for Class-based views is not very good. I don't see how I could get several different views that belong to the same class using that tool. Class-based views seems to be an abstraction that allows quickly building common views, not building several different views that share common behavior based on the request or arg data.</p>


jovialbard (on April 22, 2013):
<p>I'm hasty and may have been looking at the wrong section of the docs. I will continue looking into class-based views and see if the functionality I want is buried in here somewhere past all the basic usages that mostly just seem to make it easy to implement common cases with less code.</p>


jovialbard (on April 22, 2013):
<p>looking over the docs for that more thoroughly, I see how class-based views would be useful, but they are not what I am trying to accomplish. As far as I can tell they do only give you tools for easily building single veiws, not for collecting a set of views into a single controller class for capturing common functionality.</p>


jovialbard (on May 1, 2013):
<p>Thank you for the links, I will look into them.</p>


Please login first before commenting.