/
views.py
334 lines (266 loc) · 12.7 KB
/
views.py
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
# -*- coding: utf-8 -*-
"""
TODO move permission checks to the dispatch view thingee
"""
import math
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.forms import Form
from django.http import HttpResponseForbidden
from django.http import Http404
from django.utils.functional import cached_property
from django.views.generic.edit import DeletionMixin
from django.views.generic import ListView
from django.views.generic import TemplateView
from django.views.generic.edit import FormView
from mongoengine.fields import EmbeddedDocumentField, ListField
from mongonaut.forms import MongoModelForm
from mongonaut.mixins import MongonautFormViewMixin
from mongonaut.mixins import MongonautViewMixin
from mongonaut.utils import is_valid_object_id
class IndexView(MongonautViewMixin, ListView):
"""Lists all the apps with mongoadmins attached."""
template_name = "mongonaut/index.html"
queryset = []
permission = 'has_view_permission'
def get_queryset(self):
return self.get_mongoadmins()
class DocumentListView(MongonautViewMixin, FormView):
"""
Lists individual mongoengine documents for a model.
:args: <app_label> <document_name>
TODO - Make a generic document fetcher method
"""
form_class = Form
success_url = '/'
template_name = "mongonaut/document_list.html"
permission = 'has_view_permission'
documents_per_page = 25
#def dispatch(self, *args, **kwargs):
# self.set_mongoadmin()
# self.set_permissions()
# return super(DocumentListView, self).dispatch(*args, **kwargs)
def get_qset(self, queryset, q):
"""Performs filtering against the default queryset returned by
mongoengine.
"""
if self.mongoadmin.search_fields and q:
params = {}
for field in self.mongoadmin.search_fields:
if field == 'id':
# check to make sure this is a valid ID, otherwise we just continue
if is_valid_object_id(q):
return queryset.filter(pk=q)
continue
search_key = "{field}__icontains".format(field=field)
params[search_key] = q
queryset = queryset.filter(**params)
return queryset
@cached_property
def get_queryset(self):
"""Replicates Django CBV `get_queryset()` method, but for MongoEngine.
"""
self.set_mongonaut_base()
self.set_mongoadmin()
self.document = getattr(self.models, self.document_name)
queryset = self.document.objects.all()
if self.mongoadmin.ordering:
queryset = queryset.order_by(*self.mongoadmin.ordering)
# search. move this to get_queryset
# search. move this to get_queryset
q = self.request.GET.get('q')
queryset = self.get_qset(queryset, q)
### Start pagination
### Note:
### Can't use Paginator in Django because mongoengine querysets are
### not the same as Django ORM querysets and it broke.
# Make sure page request is an int. If not, deliver first page.
try:
self.page = int(self.request.GET.get('page', '1'))
except ValueError:
self.page = 1
obj_count = queryset.count()
self.total_pages = math.ceil(obj_count / self.documents_per_page)
if self.page < 1:
self.page = 1
if self.page > self.total_pages:
self.page = self.total_pages
start = (self.page - 1) * self.documents_per_page
end = self.page * self.documents_per_page
queryset = queryset[start:end] if obj_count else queryset
return queryset
def get_initial(self):
"""Used during adding/editing of data."""
self.query = self.get_queryset()
mongo_ids = {'mongo_id': [unicode(x.id) for x in self.query]}
return mongo_ids
def get_context_data(self, **kwargs):
"""Injects data into the context to replicate CBV ListView."""
context = super(DocumentListView, self).get_context_data(**kwargs)
context = self.set_permissions_in_context(context)
if not context['has_view_permission']:
return HttpResponseForbidden("You do not have permissions to view this content.")
context['object_list'] = self.get_queryset()
context['document'] = self.document
context['app_label'] = self.app_label
context['document_name'] = self.document_name
context['request'] = self.request
# pagination bits
context['page'] = self.page
context['documents_per_page'] = self.documents_per_page
if self.page > 1:
previous_page_number = self.page - 1
else:
previous_page_number = None
if self.page < self.total_pages:
next_page_number = self.page + 1
else:
next_page_number = None
context['previous_page_number'] = previous_page_number
context['has_previous_page'] = previous_page_number is not None
context['next_page_number'] = next_page_number
context['has_next_page'] = next_page_number is not None
context['total_pages'] = self.total_pages
# Part of upcoming list view form functionality
if self.queryset.count():
context['keys'] = ['id', ]
# Show those items for which we've got list_fields on the mongoadmin
for key in [x for x in self.mongoadmin.list_fields if x != 'id' and x in self.document._fields.keys()]:
# TODO - Figure out why this EmbeddedDocumentField and ListField breaks this view
# Note - This is the challenge part, right? :)
if isinstance(self.document._fields[key], EmbeddedDocumentField):
continue
if isinstance(self.document._fields[key], ListField):
continue
context['keys'].append(key)
if self.mongoadmin.search_fields:
context['search_field'] = True
return context
def post(self, request, *args, **kwargs):
"""Creates new mongoengine records."""
# TODO - make sure to check the rights of the poster
#self.get_queryset() # TODO - write something that grabs the document class better
form_class = self.get_form_class()
form = self.get_form(form_class)
mongo_ids = self.get_initial()['mongo_id']
for form_mongo_id in form.data.getlist('mongo_id'):
for mongo_id in mongo_ids:
if form_mongo_id == mongo_id:
self.document.objects.get(pk=mongo_id).delete()
return self.form_invalid(form)
class DocumentDetailView(MongonautViewMixin, TemplateView):
""" :args: <app_label> <document_name> <id> """
template_name = "mongonaut/document_detail.html"
permission = 'has_view_permission'
def get_context_data(self, **kwargs):
context = super(DocumentDetailView, self).get_context_data(**kwargs)
self.set_mongoadmin()
context = self.set_permissions_in_context(context)
self.document_type = getattr(self.models, self.document_name)
self.ident = self.kwargs.get('id')
self.document = self.document_type.objects.get(pk=self.ident)
context['document'] = self.document
context['app_label'] = self.app_label
context['document_name'] = self.document_name
context['keys'] = ['id', ]
context['embedded_documents'] = []
context['list_fields'] = []
for key in sorted([x for x in self.document._fields.keys() if x != 'id']):
# TODO - Figure out why this EmbeddedDocumentField and ListField breaks this view
# Note - This is the challenge part, right? :)
if isinstance(self.document._fields[key], EmbeddedDocumentField):
context['embedded_documents'].append(key)
continue
if isinstance(self.document._fields[key], ListField):
context['list_fields'].append(key)
continue
context['keys'].append(key)
return context
class DocumentEditFormView(MongonautViewMixin, FormView, MongonautFormViewMixin):
""" :args: <app_label> <document_name> <id> """
template_name = "mongonaut/document_edit_form.html"
form_class = Form
success_url = '/'
permission = 'has_edit_permission'
def get_success_url(self):
self.set_mongonaut_base()
return reverse('document_detail_edit_form', kwargs={'app_label': self.app_label, 'document_name': self.document_name, 'id': self.kwargs.get('id')})
def get_context_data(self, **kwargs):
context = super(DocumentEditFormView, self).get_context_data(**kwargs)
self.set_mongoadmin()
context = self.set_permissions_in_context(context)
self.document_type = getattr(self.models, self.document_name)
self.ident = self.kwargs.get('id')
self.document = self.document_type.objects.get(pk=self.ident)
context['document'] = self.document
context['app_label'] = self.app_label
context['document_name'] = self.document_name
context['form_action'] = reverse('document_detail_edit_form', args=[self.kwargs.get('app_label'),
self.kwargs.get('document_name'),
self.kwargs.get('id')])
return context
def get_form(self, Form):
self.set_mongoadmin()
context = self.set_permissions_in_context({})
if not context['has_edit_permission']:
return HttpResponseForbidden("You do not have permissions to edit this content.")
self.document_type = getattr(self.models, self.document_name)
self.ident = self.kwargs.get('id')
try:
self.document = self.document_type.objects.get(pk=self.ident)
except self.document_type.DoesNotExist:
raise Http404
self.form = Form()
if self.request.method == 'POST':
self.form = self.process_post_form('Your changes have been saved.')
else:
self.form = MongoModelForm(model=self.document_type, instance=self.document).get_form()
return self.form
class DocumentAddFormView(MongonautViewMixin, FormView, MongonautFormViewMixin):
""" :args: <app_label> <document_name> <id> """
template_name = "mongonaut/document_add_form.html"
form_class = Form
success_url = '/'
permission = 'has_add_permission'
def get_success_url(self):
self.set_mongonaut_base()
return reverse('document_detail', kwargs={'app_label': self.app_label, 'document_name': self.document_name, 'id': str(self.new_document.id)})
def get_context_data(self, **kwargs):
""" TODO - possibly inherit this from DocumentEditFormView. This is same thing minus:
self.ident = self.kwargs.get('id')
self.document = self.document_type.objects.get(pk=self.ident)
"""
context = super(DocumentAddFormView, self).get_context_data(**kwargs)
self.set_mongoadmin()
context = self.set_permissions_in_context(context)
self.document_type = getattr(self.models, self.document_name)
context['app_label'] = self.app_label
context['document_name'] = self.document_name
context['form_action'] = reverse('document_detail_add_form', args=[self.kwargs.get('app_label'),
self.kwargs.get('document_name')])
return context
def get_form(self, Form):
self.set_mongonaut_base()
self.document_type = getattr(self.models, self.document_name)
self.form = Form()
if self.request.method == 'POST':
self.form = self.process_post_form('Your new document has been added and saved.')
else:
self.form = MongoModelForm(model=self.document_type).get_form()
return self.form
class DocumentDeleteView(DeletionMixin, MongonautViewMixin, TemplateView):
""" :args: <app_label> <document_name> <id>
TODO - implement a GET view for confirmation
"""
success_url = "/"
template_name = "mongonaut/document_delete.html"
def get_success_url(self):
self.set_mongonaut_base()
messages.add_message(self.request, messages.INFO, 'Your document has been deleted.')
return reverse('document_list', kwargs={'app_label': self.app_label, 'document_name': self.document_name})
def get_object(self):
self.set_mongoadmin()
self.document_type = getattr(self.models, self.document_name)
self.ident = self.kwargs.get('id')
self.document = self.document_type.objects.get(pk=self.ident)
return self.document