- April 18, 2013
- Not specified
- 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.
1 2 3 4 5 6 7 8
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
- Browser-native date input field by kytta 1 month, 1 week ago
- Generate and render HTML Table by LLyaudet 1 month, 2 weeks ago
- My firs Snippets by GutemaG 1 month, 3 weeks ago
- FileField having auto upload_to path by junaidmgithub 3 months ago
- LazyPrimaryKeyRelatedField by LLyaudet 3 months, 1 week ago