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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2015 Étienne Loks <etienne.loks_AT_peacefrogsDOTnet>
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# See the file COPYING for details.
"""
Settings for administration pages
"""
import datetime
from django import forms
from django.conf import settings
from django.contrib import admin, messages
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext_lazy as _
try:
from chimere import tasks
except ImportError:
pass
from chimere.forms import MarkerAdminForm, RouteAdminForm, AreaAdminForm,\
NewsAdminForm, CategoryAdminForm, ImporterAdminForm, OSMForm, \
PageAdminForm, PictureFileAdminForm, MultimediaFileAdminForm
from chimere.models import Category, Icon, SubCategory, Marker, \
PropertyModel, News, Route, Area, ColorTheme, Color, \
MultimediaFile, PictureFile, Importer, Layer, AreaLayers,\
PropertyModelChoice, MultimediaExtension, Page,\
get_areas_for_user, get_users_by_area, ImporterKeyCategories
from chimere.utils import unicode_normalize, ShapefileManager, KMLManager,\
CSVManager
def disable(modeladmin, request, queryset):
for item in queryset:
item.status = 'D'
item.save()
disable.short_description = _(u"Disable")
def validate(modeladmin, request, queryset):
for item in queryset:
item.status = 'A'
item.save()
validate.short_description = _(u"Validate")
def export_to_kml(modeladmin, request, queryset):
u"""
Export data to KML
"""
filename, result = KMLManager.export(queryset)
response = HttpResponse(result,
mimetype='application/vnd.google-earth.kml+xml')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
export_to_kml.short_description = _(u"Export to KML")
def export_to_shapefile(modeladmin, request, queryset):
u"""
Export data to Shapefile
"""
filename, zip_stream = ShapefileManager.export(queryset)
# Stick it all in a django HttpResponse
response = HttpResponse()
response['Content-Disposition'] = 'attachment; filename=%s.zip' % filename
response['Content-length'] = str(len(zip_stream))
response['Content-Type'] = 'application/zip'
response.write(zip_stream)
return response
export_to_shapefile.short_description = _(u"Export to Shapefile")
def export_to_csv(modeladmin, request, queryset):
u"""
Export data to CSV
"""
filename, result = CSVManager.export(queryset)
response = HttpResponse(result, mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=%s' % filename
return response
export_to_csv.short_description = _(u"Export to CSV")
def managed_modified(modeladmin, request, queryset):
# not very clean... There is must be a better way to do that
redirect_url = request.get_full_path().split('admin_modification')[0]
if queryset.count() != 1 and len(set([i.ref_item or i
for i in queryset.all()])) != 1:
messages.error(request, _(u"Only one item can be managed at a "
u"time."))
return HttpResponseRedirect(redirect_url)
item = queryset.all()[0]
if not item.ref_item or item.ref_item == item:
try:
item = modeladmin.model.objects.filter(ref_item=item
).exclude(pk=item.pk).all()[0]
except IndexError:
messages.error(request, _(u"No modified item associated "
u"to the selected item."))
return HttpResponseRedirect(redirect_url)
item_ref = item.ref_item
if request.POST.get('rapprochement'):
couple = [(item, item_ref)]
if hasattr(item, 'associated_marker'):
couple.append((item.associated_marker.all()[0],
item_ref.associated_marker.all()[0]))
updated = dict(request.POST)
# clean
for k in ('action', 'rapprochement', 'index', '_selected_action'):
if k in updated:
updated.pop(k)
for idx, cpl in enumerate(couple):
it, it_ref = cpl
# don't copy geometry of associated items
if idx:
for k in ('route', 'point'):
if k in updated:
updated.pop(k)
updated_keys = updated.keys()
if it.status == 'I':
updated_keys.append('import_version')
for k in updated_keys:
if k != 'import_version' and not request.POST[k]:
continue
if hasattr(it_ref, k):
c_value = getattr(it_ref, k)
if hasattr(c_value, 'select_related'):
c_value.clear()
for val in getattr(it, k).all():
c_value.add(val)
else:
setattr(it_ref, k, getattr(it, k))
it_ref.save()
elif k.startswith('property_'):
try:
pm = PropertyModel.get(pk=int(k[len('property_'):]))
it_ref.setProperty(pm, it.getProperty(pm))
except (ValueError, ObjectDoesNotExist):
pass
if hasattr(item, 'associated_marker'):
for it in item.associated_marker.all():
it.delete()
item.delete()
messages.success(request, _(u"Modified item traited."))
return HttpResponseRedirect(redirect_url)
return render_to_response('admin/chimere/managed_modified.html',
{'item':item, 'item_ref':item_ref},
context_instance=RequestContext(request))
managed_modified.short_description = _(u"Managed modified items")
class PictureInline(admin.TabularInline):
model = PictureFile
extra = 1
ordering = ('order',)
form = PictureFileAdminForm
readonly_fields = ('height', 'width')
exclude = ('thumbnailfile', 'thumbnailfile_height', 'thumbnailfile_width')
class MultimediaInline(admin.TabularInline):
model = MultimediaFile
extra = 1
ordering = ('order',)
form = MultimediaFileAdminForm
class MarkerAdmin(admin.ModelAdmin):
"""
Specialized the Point field.
"""
search_fields = ("name",)
list_display = ('name', 'status', 'start_date', 'end_date')
list_filter = ('status', 'categories', 'start_date', 'end_date')
actions = [validate, disable, managed_modified, export_to_kml,
export_to_shapefile, export_to_csv]
exclude = ['submiter_session_key', 'import_key', 'import_version',
'available_date', 'ref_item']
readonly_fields = ['submiter_email', 'submiter_comment', 'import_source',
'submiter_name', 'ref_item', 'modified_since_import', 'route']
form = MarkerAdminForm
fieldsets = ((None, {
'fields': ['point', 'name', 'status', 'categories',
'description', 'start_date', 'end_date']
}),
(_(u"Submitter"), {
'classes':('collapse',),
'fields': ('submiter_name', 'submiter_email',
'submiter_comment')
}),
(_(u"Import"), {
'classes':('collapse',),
'fields': ('not_for_osm', 'modified_since_import',
'import_source', 'origin', 'license')
}),
(_(u"Associated items"), {
'classes':('collapse',),
'fields': ('ref_item', 'route',)
}),
)
inlines = [MultimediaInline, PictureInline]
has_properties = True
def __init__(self, *args, **kwargs):
"""
Manage properties in fieldsets.
"""
if self.has_properties:
main_fields = self.fieldsets[0][1]['fields']
for pm in PropertyModel.objects.filter(available=True).order_by('order'
).all():
pm_name = pm.getNamedId()
if pm_name not in main_fields:
main_fields.append(pm_name)
super(MarkerAdmin, self).__init__(*args, **kwargs)
def queryset(self, request):
qs = self.model._default_manager.get_query_set()
if not request.user.is_superuser:
areas = get_areas_for_user(request.user)
contained = Q()
for area in areas:
contained = contained | area.getIncludeMarker()
qs = qs.filter(contained)
ordering = self.ordering or ()
if ordering:
qs = qs.order_by(*ordering)
return qs.distinct()
def admin_modification(self, request, item_id):
'''
Redirect to the marker modification form
'''
return managed_modified(self, request,
Marker.objects.filter(pk=item_id))
def get_urls(self):
from django.conf.urls.defaults import patterns, url
urls = super(MarkerAdmin, self).get_urls()
my_urls = patterns('',
url(r'^admin_modification/(?P<item_id>\d+)/$',
self.admin_site.admin_view(self.admin_modification),
name='admin-modification'),
)
return my_urls + urls
class RouteAdmin(MarkerAdmin):
"""
Specialized the Route field.
"""
search_fields = ("name",)
list_display = ('name', 'status')
list_filter = ('status', 'categories')
exclude = ['height', 'width']
form = RouteAdminForm
readonly_fields = ('associated_file', 'ref_item', 'has_associated_marker')
actions = [validate, disable, managed_modified, export_to_kml,
export_to_shapefile, export_to_csv]
fieldsets = ((None, {
'fields': ['route', 'name', 'status', 'categories',
'start_date', 'end_date']
}),
(_(u"Submitter"), {
'classes':('collapse',),
'fields': ('submiter_name', 'submiter_email',
'submiter_comment')
}),
(_(u"Import"), {
'classes':('collapse',),
'fields': ('modified_since_import', 'import_source',
'origin', 'license')
}),
(_(u"Associated items"), {
'classes':('collapse',),
'fields': ('ref_item', 'associated_file',
'has_associated_marker')
}),
)
inlines = []
has_properties = False
def queryset(self, request):
qs = self.model._default_manager.get_query_set()
if not request.user.is_superuser:
areas = get_areas_for_user(request.user)
contained = Q()
for area in areas:
contained = contained | area.getIncludeRoute()
qs = qs.filter(contained)
ordering = self.ordering or ()
if ordering:
qs = qs.order_by(*ordering)
return qs
def admin_modification(self, request, item_id):
'''
Redirect to the route modification form
'''
return managed_modified(self, request,
Route.objects.filter(pk=item_id))
class LayerInline(admin.TabularInline):
model = AreaLayers
extra = 1
class AreaAdmin(admin.ModelAdmin):
"""
Specialized the area field.
"""
form = AreaAdminForm
exclude = ['upper_left_corner', 'lower_right_corner']
inlines = [LayerInline]
list_display = ['name', 'order', 'available', 'default']
def importing(modeladmin, request, queryset):
for importer in queryset:
importer.state = unicode(tasks.IMPORT_MESSAGES['import_pending'][0])
importer.save()
tasks.importing(importer.pk)
importing.short_description = _(u"Import")
def cancel_import(modeladmin, request, queryset):
for importer in queryset:
importer.state = tasks.IMPORT_MESSAGES['import_cancel'][0]
importer.save()
cancel_import.short_description = _(u"Cancel import")
def cancel_export(modeladmin, request, queryset):
for importer in queryset:
importer.state = tasks.IMPORT_MESSAGES['export_cancel'][0]
importer.save()
cancel_export.short_description = _(u"Cancel export")
def export_to_osm(modeladmin, request, queryset):
if queryset.count() > 1:
messages.error(request, _(u"Can manage only one OSM export at a time."))
return HttpResponseRedirect(request.get_full_path())
importer = queryset.all()[0]
if Marker.objects.filter(categories__in=importer.categories.all(),
status='I').count():
messages.error(request, _(u"You must treat all item with the status "\
u"\"imported\" before exporting to OSM."))
return HttpResponseRedirect(request.get_full_path())
if importer.importer_type != 'OSM':
messages.error(request, _(u"Only OSM importer are managed for export."))
return HttpResponseRedirect(request.get_full_path())
item_nb = Marker.objects.filter(status='A',
categories=importer.categories.all(),
not_for_osm=False, modified_since_import=True,
route=None).count()
if not item_nb:
messages.error(request, _(u"No point of interest are concerned by this "
u"export."))
return HttpResponseRedirect(request.get_full_path())
form = None
if request.method == 'POST' and (
'email' in request.POST or 'api' in request.POST
or 'password' in request.POST):
form = OSMForm(request.POST)
if form.is_valid():
importer.state = unicode(tasks.IMPORT_MESSAGES['export_pending'][0])
importer.save()
tasks.exporting(importer.pk, form.cleaned_data)
messages.success(request, _(u"Export launched."))
return HttpResponseRedirect(request.get_full_path())
else:
form = OSMForm()
msg_item = _(u"%s point(s) of interest concerned by this export before "\
u"bounding box filter.") % item_nb
return render_to_response('admin/chimere/osm_export.html', {'item':importer,
'form':form, 'msg_item':msg_item},
context_instance=RequestContext(request))
export_to_osm.short_description = _(u"Export to osm")
class ImporterKeyInline(admin.TabularInline):
model = ImporterKeyCategories
extra = 1
class ImporterAdmin(admin.ModelAdmin):
form = ImporterAdminForm
list_display = ('importer_type', 'display_categories', 'default_name',
'source', 'state', 'filtr')
list_filter = ('importer_type', 'categories')
readonly_fields = ('state',)
actions = [importing, cancel_import, export_to_osm, cancel_export]
inlines = [ImporterKeyInline]
admin.site.register(Importer, ImporterAdmin)
class PageAdmin(admin.ModelAdmin):
"""
Use the TinyMCE widget for the page content
"""
form = PageAdminForm
class PropertyModelAdmin(admin.ModelAdmin):
list_display = ('name', 'order', 'available')
class NewsAdmin(admin.ModelAdmin):
"""
Use the TinyMCE widget for the news content
"""
form = NewsAdminForm
class SubcatInline(admin.TabularInline):
model = SubCategory
extra = 1
class CategoryAdmin(admin.ModelAdmin):
"""
Use the TinyMCE widget for categories
"""
form = CategoryAdminForm
inlines = [SubcatInline]
list_display = ['name', 'order']
class ColorInline(admin.TabularInline):
model = Color
class ColorThemeAdmin(admin.ModelAdmin):
inlines = [ColorInline,]
class IconAdmin(admin.ModelAdmin):
exclude = ['height', 'width']
list_display = ['name']
class PropertyModelChoiceInline(admin.TabularInline):
model = PropertyModelChoice
extra = 1
class PropertyModelAdmin(admin.ModelAdmin):
inlines = [PropertyModelChoiceInline]
# register of differents database fields
admin.site.register(Page, PageAdmin)
admin.site.register(News, NewsAdmin)
admin.site.register(Category, CategoryAdmin)
admin.site.register(Icon, IconAdmin)
admin.site.register(Marker, MarkerAdmin)
admin.site.register(Route, RouteAdmin)
if not settings.CHIMERE_HIDE_PROPERTYMODEL:
admin.site.register(PropertyModel, PropertyModelAdmin)
admin.site.register(Area, AreaAdmin)
admin.site.register(ColorTheme, ColorThemeAdmin)
admin.site.register(Layer)
|