Package: django-viewsets
ContentsProblematicSolutionInstallationUsageProvided views and urlsBasic useAdvanced useBasic AttributesAdvanced attributesProblematicWhen having a look atRuby on Rails, I discovered a nice feature that was
missing in Django:controllers.
Contrary to what I often read, views in Django are not really equivalent to
controllers in Rails.  A Rails controller basically isa set of Django
views and Django URL patterns.  Apart from driving off boring URL work, this
is a clean way to group views that belongs to the same model.Any good djangonaut would make the connection with generic views − especiallyclass-based.
This is the easiest solution to avoid repeating the same code with a few
changes.  But this is not simplifying URL patterns and we often have to define
such files:# views.py
from django.views.generic import ListView, DetailView  # and so on…
from .models import Example


class ExampleListView(ListView):
    model = Example


class ExampleDetailView(DetailView):
    model = Example

# and so on…# urls.py
from django.conf.urls import patterns, url
from .views import *


urlpatterns = patterns('',
    url('^examples/$', ExampleListView.as_view(), name='example_index'),
    url('^examples/(?P<pk>\d+)$', ExampleDetailView.as_view(),
        name='example_detail'),
    # and so on…
)With a single model, this looks easy.  With complex applications containing
dozens of models,this looks painful− and definitely not DRY[1].Solutiondjango-viewsetsproposes a solution inspired of Rails controllers.ViewSetis a class that builds a set of URL patterns from a set of
class-based generic views.  It is designed to be overridable, so that it fits
standard as well as advanced use.Installation[sudo] pip installdjango-viewsetsYou don’t have to change your projectsettings.py.UsageModelViewSetProvided views and urlsGeneric viewURLURL nameListViewyour-models/your-model_indexDetailViewyour-models/[pk]your-model_detailCreateViewyour-models/create/your-model_createUpdateViewyour-models/[pk]/updateyour-model_updateDeleteViewyour-models/[pk]/deleteyour-model_deleteBasic useIn your application (or project)urls.py:from django.conf.urls import patterns, url, include
from viewsets import ModelViewSet
from .models import YourModel

urlpatterns = patterns('',
    url('', include(ModelViewSet(YourModel).urls)),
)You can also provide otherbasic attributesas keyword arguments.  For
example, if you want to use slugs instead of primary keys in URL patterns,
lines 2 and 6 become:from viewsets import ModelViewSet, SLUG  # line 2
url('', include(ModelViewSet(YourModel, id_pattern=SLUG).urls)),  # line 6Advanced useThis allow more customization.In your applicationviews.py:from viewsets import ModelViewSet
from .models import YourModel

class YourModelViewSet(ModelViewSet):
    model = YourModelIn your application (or project)urls.py:from django.conf.urls import patterns, url, include
from .views import YourModelViewSet

urlpatterns = patterns('',
    url('', include(YourModelViewSet().urls)),
)What is interesting in this use is that you can easily customize views and
urls.  Let’s say you want to use primary keys in update and delete url
patterns, but you want to use slugs in detail view.  The fastest way to do it
is:from viewsets import ModelViewSet, SLUG

class CustomModelViewSet(ModelViewSet):
    def __init__(self, *args, **kwargs):
        self.views['detail_view']['pattern'] = SLUG
        super(CustomModelViewSet, self).__init__(*args, **kwargs)Here we don’t set themodelattribute, so thatCustomModelViewSetcan
be used for any of your models.  Of course, you can now useCustomModelViewSetwithbasic useas well asAdvanced use.  And we
could have setmodel, if this viewset was meant to be used only with a
specific model.Basic AttributesmodelThe model class from which ModelViewSet will create views and urls.  This is
the only mandatory attribute.base_url_patternOverridesyour-modelsin all URL patterns.  Calculated frommodel._meta.verbose_name_pluralif unset.base_url_nameOverridesyour-modelin all URL names.  Calculated frommodel._meta.verbose_nameif unset.id_patternOverrides[pk]in all URL patterns.  You can either useviewsets.PKorviewsets.SLUG.excluded_viewsA sequence of keys from theviews.  Unset by default.
Example:('create_view','delete_view',).namespaceSet this if your application has a URL namespace.  It is used to redirect
tomain_viewin delete_view.  You can also setmain_url.main_viewUsed to calculatemain_url.'list_view'by default.main_urlThe main url where delete_view redirects.  If set,main_viewis ignored.Advanced attributesviewsDictionary defining views and URLs.  CRUD[2]by default.[1]Don’t Repeat Yourself[2]Create Read Update Delete