summaryrefslogtreecommitdiff
path: root/chimere/admin.py
blob: ad247066a772f240c913041e1ee8ee8a595c9659 (plain)
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2008-2012  É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,\
     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
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):
    if queryset.count() != 1:
        messages.error(request, _(u"Only one item can be managed at a "
                                  u"time."))
        return HttpResponseRedirect(request.get_full_path())

    item = queryset.all()[0]
    if not item.status == 'M':
        try:
            item = modeladmin.model.objects.get(ref_item=item, status='M')
        except ObjectDoesNotExist:
            messages.error(request, _(u"No modified item associated "
                                      u"to the selected item."))
            return HttpResponseRedirect(request.get_full_path())
    item_ref = item.ref_item
    if request.POST.get('rapprochement'):
        couple = [(item, item_ref)]
        if hasattr(item, 'associated_marker'):
            couple.append((item.associated_marker, item_ref.associated_marker))
        for it, it_ref in couple:
            for k in request.POST:
                if not request.POST[k]:
                    continue
                if hasattr(it_ref, k):
                    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(request.get_full_path())
    return render_to_response('admin/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')
    list_filter = ('status', 'categories')
    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']
    form = MarkerAdminForm
    inlines = [MultimediaInline, PictureInline]

    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()

class RouteAdmin(admin.ModelAdmin):
    """
    Specialized the Route field.
    """
    search_fields = ("name",)
    list_display = ('name', 'status')
    list_filter = ('status', 'categories')
    exclude = ['height', 'width']
    form = RouteAdminForm
    readonly_fields = ('associated_file',)
    actions = [validate, disable, managed_modified, export_to_kml,
               export_to_shapefile, export_to_csv]

    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

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):
    importers = modeladmin.model.objects.filter(importer_type='OSM')
    for importer in queryset:
        importer.state = unicode(tasks.IMPORT_MESSAGES['export_pending'][0])
        importer.save()
        tasks.exporting(importer.pk)
export_to_osm.short_description = _(u"Export to osm")

class ImporterAdmin(admin.ModelAdmin):
    form = ImporterAdminForm
    list_display = ('display_categories', 'default_name', 'importer_type',
                    'source', 'state', 'filtr')
    list_filter = ('importer_type', 'categories')
    readonly_fields = ('state',)
    actions = [importing, cancel_import, export_to_osm, cancel_export]
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)
admin.site.register(PropertyModel, PropertyModelAdmin)
admin.site.register(Area, AreaAdmin)
admin.site.register(ColorTheme, ColorThemeAdmin)
admin.site.register(Layer)