1
|
from datetime import datetime
|
2
|
from dateutil.relativedelta import relativedelta
|
3
|
|
4
|
from django import forms
|
5
|
from django.views.generic import list as list_cbv, edit, base, detail
|
6
|
from django.shortcuts import get_object_or_404
|
7
|
from django.http import Http404, HttpResponseRedirect
|
8
|
from django.core.urlresolvers import resolve
|
9
|
from django.core.exceptions import ImproperlyConfigured
|
10
|
|
11
|
from calebasse.ressources.models import Service
|
12
|
|
13
|
class ReturnToObjectMixin(object):
|
14
|
def get_success_url(self):
|
15
|
return '../#object-' + str(self.get_object().pk)
|
16
|
|
17
|
class ServiceFormMixin(object):
|
18
|
def get_form_kwargs(self):
|
19
|
kwargs = super(ServiceFormMixin, self).get_form_kwargs()
|
20
|
kwargs['service'] = self.service
|
21
|
return kwargs
|
22
|
|
23
|
class ServiceViewMixin(object):
|
24
|
service = None
|
25
|
date = None
|
26
|
popup = False
|
27
|
|
28
|
def dispatch(self, request, **kwargs):
|
29
|
self.popup = request.GET.get('popup')
|
30
|
if 'service' in kwargs:
|
31
|
self.service = get_object_or_404(Service, slug=kwargs['service'])
|
32
|
if 'date' in kwargs:
|
33
|
try:
|
34
|
self.date = datetime.strptime(kwargs.get('date'),
|
35
|
'%Y-%m-%d').date()
|
36
|
except (TypeError, ValueError):
|
37
|
raise Http404
|
38
|
return super(ServiceViewMixin, self).dispatch(request, **kwargs)
|
39
|
|
40
|
def get_context_data(self, **kwargs):
|
41
|
context = super(ServiceViewMixin, self).get_context_data(**kwargs)
|
42
|
context['url_name'] = resolve(self.request.path).url_name
|
43
|
context['popup'] = self.popup
|
44
|
if self.service is not None:
|
45
|
context['service'] = self.service.slug
|
46
|
context['service_name'] = self.service.name
|
47
|
|
48
|
if self.date is not None:
|
49
|
context['date'] = self.date
|
50
|
context['previous_day'] = self.date + relativedelta(days=-1)
|
51
|
context['next_day'] = self.date + relativedelta(days=1)
|
52
|
context['previous_month'] = self.date + relativedelta(months=-1)
|
53
|
context['next_month'] = self.date + relativedelta(months=1)
|
54
|
return context
|
55
|
|
56
|
class TemplateView(ServiceViewMixin, base.TemplateView):
|
57
|
pass
|
58
|
|
59
|
class ModelNameMixin(object):
|
60
|
def get_context_data(self, **kwargs):
|
61
|
ctx = super(ModelNameMixin, self).get_context_data(**kwargs)
|
62
|
ctx['model_verbose_name_plural'] = self.model._meta.verbose_name_plural
|
63
|
ctx['model_verbose_name'] = self.model._meta.verbose_name
|
64
|
return ctx
|
65
|
|
66
|
class ListView(ModelNameMixin, ServiceViewMixin, list_cbv.ListView):
|
67
|
pass
|
68
|
|
69
|
|
70
|
class CreateView(ModelNameMixin, ServiceViewMixin, edit.CreateView):
|
71
|
pass
|
72
|
|
73
|
|
74
|
class DeleteView(ModelNameMixin, ServiceViewMixin, edit.DeleteView):
|
75
|
pass
|
76
|
|
77
|
|
78
|
class UpdateView(ModelNameMixin, ServiceViewMixin, edit.UpdateView):
|
79
|
pass
|
80
|
|
81
|
class FormView(ServiceViewMixin, edit.FormView):
|
82
|
pass
|
83
|
|
84
|
class ContextMixin(object):
|
85
|
"""
|
86
|
A default context mixin that passes the keyword arguments received by
|
87
|
get_context_data as the template context.
|
88
|
"""
|
89
|
|
90
|
def get_context_data(self, **kwargs):
|
91
|
if 'view' not in kwargs:
|
92
|
kwargs['view'] = self
|
93
|
return kwargs
|
94
|
|
95
|
class MultiFormMixin(ContextMixin):
|
96
|
"""
|
97
|
A mixin that provides a way to show and handle multiple forms in a request.
|
98
|
"""
|
99
|
|
100
|
initial = {}
|
101
|
initials = {}
|
102
|
forms_classes = None
|
103
|
success_url = None
|
104
|
|
105
|
def get_prefixes(self):
|
106
|
return self.forms_classes.keys()
|
107
|
|
108
|
def get_initial(self, prefix):
|
109
|
"""
|
110
|
Returns the initial data to use for forms on this view.
|
111
|
"""
|
112
|
return self.initials.get(prefix, self.initial).copy()
|
113
|
|
114
|
def get_form_class(self, prefix):
|
115
|
"""
|
116
|
Returns the form class to use in this view
|
117
|
"""
|
118
|
return self.forms_classes[prefix]
|
119
|
|
120
|
def get_form(self, form_class, prefix):
|
121
|
"""
|
122
|
Returns an instance of the form to be used in this view.
|
123
|
"""
|
124
|
return form_class(**self.get_form_kwargs(prefix))
|
125
|
|
126
|
def get_current_prefix(self):
|
127
|
"""
|
128
|
Returns the current prefix by parsing first keys in POST
|
129
|
"""
|
130
|
keys = self.request.POST.keys() or self.request.FILES.keys()
|
131
|
if not keys:
|
132
|
return None
|
133
|
return keys[0].split('-', 1)[0]
|
134
|
|
135
|
def get_forms(self):
|
136
|
"""
|
137
|
Returns the dictionnary of forms instances
|
138
|
"""
|
139
|
form_instances = {}
|
140
|
for prefix in self.get_prefixes():
|
141
|
form_instances[prefix] = self.get_form(self.get_form_class(prefix), prefix)
|
142
|
return form_instances
|
143
|
|
144
|
def get_form_kwargs(self, prefix):
|
145
|
"""
|
146
|
Returns the keyword arguments for instantiating the form.
|
147
|
"""
|
148
|
kwargs = {'initial': self.get_initial(prefix),
|
149
|
'prefix': prefix }
|
150
|
if self.request.method in ('POST', 'PUT') \
|
151
|
and prefix == self.get_current_prefix():
|
152
|
kwargs.update({
|
153
|
'data': self.request.POST,
|
154
|
'files': self.request.FILES,
|
155
|
})
|
156
|
return kwargs
|
157
|
|
158
|
def get_success_url(self):
|
159
|
"""
|
160
|
Returns the supplied success URL.
|
161
|
"""
|
162
|
if self.success_url:
|
163
|
url = self.success_url
|
164
|
else:
|
165
|
raise ImproperlyConfigured(
|
166
|
"No URL to redirect to. Provide a success_url.")
|
167
|
return url
|
168
|
|
169
|
def form_valid(self, forms):
|
170
|
"""
|
171
|
If the form is valid, redirect to the supplied URL.
|
172
|
"""
|
173
|
return HttpResponseRedirect(self.get_success_url())
|
174
|
|
175
|
def form_invalid(self, forms):
|
176
|
"""
|
177
|
If the form is invalid, re-render the context data with the
|
178
|
data-filled form and errors.
|
179
|
"""
|
180
|
return self.render_to_response(self.get_context_data(forms=forms))
|
181
|
|
182
|
class MultiModelFormMixin(MultiFormMixin, detail.SingleObjectMixin):
|
183
|
"""
|
184
|
A mixin that provides a way to show and handle multiple forms or modelforms
|
185
|
in a request.
|
186
|
"""
|
187
|
|
188
|
def get_form_kwargs(self, prefix):
|
189
|
"""
|
190
|
Returns the keyword arguments for instantiating the form.
|
191
|
"""
|
192
|
kwargs = super(MultiModelFormMixin, self).get_form_kwargs(prefix)
|
193
|
if issubclass(self.get_form_class(prefix), forms.ModelForm):
|
194
|
kwargs.update({'instance': self.object})
|
195
|
return kwargs
|
196
|
|
197
|
def get_success_url(self):
|
198
|
"""
|
199
|
Returns the supplied URL.
|
200
|
"""
|
201
|
if self.success_url:
|
202
|
url = self.success_url % self.object.__dict__
|
203
|
else:
|
204
|
try:
|
205
|
url = self.object.get_absolute_url()
|
206
|
except AttributeError:
|
207
|
raise ImproperlyConfigured(
|
208
|
"No URL to redirect to. Either provide a url or define"
|
209
|
" a get_absolute_url method on the Model.")
|
210
|
return url
|
211
|
|
212
|
def form_valid(self, forms, commit=True):
|
213
|
"""
|
214
|
If the form is valid, save the associated model.
|
215
|
"""
|
216
|
form = forms[self.get_current_prefix()]
|
217
|
if hasattr(form, 'save'):
|
218
|
if isinstance(form, forms.ModelForm):
|
219
|
self.object = form.save(commit=commit)
|
220
|
else:
|
221
|
form.save()
|
222
|
return super(MultiModelFormMixin, self).form_valid(form)
|
223
|
|
224
|
def get_context_data(self, **kwargs):
|
225
|
"""
|
226
|
If an object has been supplied, inject it into the context with the
|
227
|
supplied context_object_name name.
|
228
|
"""
|
229
|
context = {}
|
230
|
if self.object:
|
231
|
context['object'] = self.object
|
232
|
context_object_name = self.get_context_object_name(self.object)
|
233
|
if context_object_name:
|
234
|
context[context_object_name] = self.object
|
235
|
context.update(kwargs)
|
236
|
return super(MultiModelFormMixin, self).get_context_data(**context)
|
237
|
|
238
|
class ProcessMultiFormView(base.View):
|
239
|
"""
|
240
|
A mixin that renders a form on GET and processes it on POST.
|
241
|
"""
|
242
|
def get(self, request, *args, **kwargs):
|
243
|
"""
|
244
|
Handles GET requests and instantiates a blank version of the form.
|
245
|
"""
|
246
|
forms = self.get_forms()
|
247
|
return self.render_to_response(self.get_context_data(forms=forms))
|
248
|
|
249
|
def post(self, request, *args, **kwargs):
|
250
|
"""
|
251
|
Handles POST requests, instantiating a form instance with the passed
|
252
|
POST variables and then checked for validity.
|
253
|
"""
|
254
|
forms = self.get_forms()
|
255
|
prefix = self.get_current_prefix()
|
256
|
if forms[prefix].is_valid():
|
257
|
return self.form_valid(forms)
|
258
|
else:
|
259
|
return self.form_invalid(forms)
|
260
|
|
261
|
# PUT is a valid HTTP verb for creating (with a known URL) or editing an
|
262
|
# object, note that browsers only support POST for now.
|
263
|
def put(self, *args, **kwargs):
|
264
|
return self.post(*args, **kwargs)
|
265
|
|
266
|
class BaseMultiFormView(MultiFormMixin, ProcessMultiFormView):
|
267
|
"""
|
268
|
A base view for displaying multiple forms
|
269
|
"""
|
270
|
|
271
|
class MultiFormView(base.TemplateResponseMixin, BaseMultiFormView):
|
272
|
"""
|
273
|
A base view for displaying multiple forms, and rendering a template reponse.
|
274
|
"""
|
275
|
|
276
|
class BaseMultiUpdateView(MultiModelFormMixin, ProcessMultiFormView):
|
277
|
"""
|
278
|
Base view for updating an existing object.
|
279
|
|
280
|
Using this base class requires subclassing to provide a response mixin.
|
281
|
"""
|
282
|
def get(self, request, *args, **kwargs):
|
283
|
self.object = self.get_object()
|
284
|
return super(BaseMultiUpdateView, self).get(request, *args, **kwargs)
|
285
|
|
286
|
def post(self, request, *args, **kwargs):
|
287
|
self.object = self.get_object()
|
288
|
return super(BaseMultiUpdateView, self).post(request, *args, **kwargs)
|
289
|
|
290
|
class MultiUpdateView(detail.SingleObjectTemplateResponseMixin, BaseMultiUpdateView):
|
291
|
"""
|
292
|
View for updating an object,
|
293
|
with a response rendered by template.
|
294
|
"""
|
295
|
template_name_suffix = '_form'
|