from django core urlresolvers import reverse from django views generic

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from django.core.urlresolvers import reverse
from django.views.generic.list_detail import *
from django.views.generic.create_update import *
from django.conf.urls.defaults import *
'''
Model based generic views
Keep all view in View.listView
Example: get url for Create Connection form in template: {{ view.listView.CreateConnection.getUrl }}
'''
def getPatterns(model):
list = ('List','Update','Create','Delete')
urlpatterns = []
for action in list:
view = globals()[action+"View"](model, action)
urlpatterns += patterns('', url(view.urlpattern, view.requestView, name=view.name))
return urlpatterns
def getUrlByName(name):
return View.listView[name].getUrl()
def getListUrl(model):
return getUrlByName('List'+model.__name__)
class View(object):
listView={}
def __init__(self, model, action):
self.model = model
self.name=action+model.__name__
self.urlpattern = r'^%s/$' % action.lower()
self.title="%s %s" % (action, model.__name__)
self.listView[self.name] = self
def do(self, *args, **kwargs):
return None # Override
def requestView(self, request, **kwargs):
return self.do(request, extra_context={'view': self}, **kwargs)
def getUrl(self):
if not hasattr(self,'url'):
self.url=reverse(self.name)
return self.url
class ListView(View):
def __init__(self, model, name):
View.__init__(self, model, name)
self.queryset= model.objects.all()
self.title = "%ss list" % model.__name__
def do(self, request, **kwargs):
return object_list(request, self.queryset, **kwargs)
class CreateView(View):
def do(self, request, **kwargs):
redirect=getListUrl(self.model)
return create_object(request, model=self.model, post_save_redirect=redirect, **kwargs)
class ObjectView(View):
def __init__(self, model, name):
View.__init__(self, model, name)
self.urlpattern = r'^%s/(?P<object_id>\d+)/$' % name
def getUrl(self):
return "Not supported (use object instead)"
class UpdateView(ObjectView):
def do(self, request, **kwargs):
return update_object(request, model=self.model, post_save_redirect=getListUrl(self.model), **kwargs)
class DeleteView(ObjectView):
def do(self, request, **kwargs):
return delete_object(request, model=self.model, post_delete_redirect=getListUrl(self.model), **kwargs)