Last active
October 4, 2015 14:45
-
-
Save valberg/9bb6c97304d304a0f27a to your computer and use it in GitHub Desktop.
A class for quickly creating CRUD views for a django model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from django.conf.urls import include, url | |
from django.views.generic import ( | |
ListView, | |
CreateView, | |
DetailView, | |
UpdateView, | |
DeleteView, | |
) | |
class CRUDMetaClass(type): | |
def __new__(mcs, name, bases, attrs): | |
model = attrs.get('model') | |
context_object_name = attrs.get( | |
'context_object_name', 'object' | |
) | |
context_object_name_plural = attrs.get( | |
'context_object_name_plural', 'object_list' | |
) | |
attrs['list_view'] = ListView.as_view( | |
model=model, | |
context_object_name=context_object_name_plural | |
) | |
attrs['create_view'] = CreateView.as_view( | |
model=model, | |
fields='__all__', | |
) | |
attrs['read_view'] = DetailView.as_view( | |
model=model, | |
context_object_name=context_object_name, | |
) | |
attrs['update_view'] = UpdateView.as_view( | |
model=model, | |
fields='__all__', | |
) | |
attrs['delete_view'] = DeleteView.as_view( | |
model=model, | |
) | |
new_class = super().__new__( | |
mcs, name, bases, attrs | |
) | |
return new_class | |
class CRUDView(object, metaclass=CRUDMetaClass): | |
""" | |
Usage: | |
urlpatterns = [ | |
url('/', CRUDView.urlpatterns(name='crud') | |
""" | |
model = None | |
def __init__(self): | |
self.create_view = CreateView.as_view( | |
model=self.model, | |
) | |
@classmethod | |
def urlpatterns(cls, namespace='', app_name=''): | |
class URLPatterns(object): | |
urlpatterns = [ | |
url( | |
r'^$', | |
cls.list_view, | |
name='list', | |
), | |
url( | |
r'^/create$', | |
cls.create_view, | |
name='create', | |
), | |
url( | |
r'^(?P<slug>\S+)$', | |
cls.read_view, | |
name='read', | |
), | |
url( | |
r'^(?P<slug>\S+)/update$', | |
cls.update_view, | |
name='update', | |
), | |
url( | |
r'^(?P<slug>\S+)/delete$', | |
cls.delete_view, | |
name='delete', | |
), | |
] | |
return include( | |
URLPatterns, | |
namespace=namespace, | |
app_name=app_name, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment