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