#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2008-2012 Étienne Loks # 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 . # 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, \ PictureFileAdminForm, MultimediaFileAdminForm from chimere.models import Category, Icon, SubCategory, Marker, \ PropertyModel, News, Route, Area, ColorTheme, Color, \ MultimediaFile, PictureFile, Importer, Layer, AreaLayers,\ get_areas_for_user, get_users_by_area from chimere.utils import unicode_normalize, ShapefileManager, KMLManager,\ CSVManager from chimere.widgets import TextareaWidget 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, managed_modified, export_to_kml, export_to_shapefile, export_to_csv] exclude = ['submiter_session_key', 'import_key', 'import_version', 'available_date'] readonly_fields = ['submiter_email', 'submiter_comment', 'import_source', '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, 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',) readonly_fields = ('state',) actions = [importing, cancel_import, export_to_osm, cancel_export] admin.site.register(Importer, ImporterAdmin) 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'] # register of differents database fields 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)