I'm using Django for the first time (I'm also new to Python in general) and I've been struggling with a certain problem related to class based views for a while now. I'm coming from PHP with Laravel, where you can have so-called "RESTful Resource Controllers".
For everyone not familiar with Laravel: the idea is that you have one controller (or view, in Django-speak) per 'resource'. This controller/view defines methods such as
I ended up writing a custom class based view that is more or less a mix of the two proposed solutions in the question.
The general idea is that I have a
ResourceView that follows the same structure as Django's
View class (it has
dispatch() methods). Just like Django's
as_view() defines a closure inside that is returned to the URLconf. This closure in turn relies on
dispatch() to dispatch the request to the correct (child) method. For this, it uses a '2d map' (dict of dicts) to determine which method should be called for which combination of route (URL) and HTTP method. The difference with Django's
View is that
as_view() is called in the URLconf with a parameter that specifies the route.
I also have a
ResourceRouter that automatically generates the URLconf corresponding to the view. This approach is somewhat inspired by how DRF handles this.
Last but not least I wrote a decorator that 'binds' the model instance to the method, so instead of the pk the model instance is passed to the view method.
The code can be found here: https://gist.github.com/Compizfox/c4e3044755417f59dc33ce97ac8ca07c