summaryrefslogtreecommitdiff
path: root/ishtar_common/admin.py
diff options
context:
space:
mode:
authorÉtienne Loks <etienne.loks@iggdrasil.net>2019-03-12 12:01:29 +0100
committerÉtienne Loks <etienne.loks@iggdrasil.net>2019-04-24 19:41:37 +0200
commit9fd090d115cd186076c170c7c227c18120388dc1 (patch)
treec39920d6475369a460e1532bc6e57a6993f3e419 /ishtar_common/admin.py
parenteca590207394bc4c257ea47a5f00de2f9de579f6 (diff)
downloadIshtar-9fd090d115cd186076c170c7c227c18120388dc1.tar.bz2
Ishtar-9fd090d115cd186076c170c7c227c18120388dc1.zip
Admin: export town to GeoJson
Diffstat (limited to 'ishtar_common/admin.py')
-rw-r--r--ishtar_common/admin.py64
1 files changed, 58 insertions, 6 deletions
diff --git a/ishtar_common/admin.py b/ishtar_common/admin.py
index df2ea399f..2ddb43cdb 100644
--- a/ishtar_common/admin.py
+++ b/ishtar_common/admin.py
@@ -24,6 +24,7 @@ import shutil
import tempfile
import urllib
import zipfile
+from StringIO import StringIO
from ajax_select import make_ajax_form
from ajax_select.fields import AutoCompleteSelectField, \
@@ -43,6 +44,7 @@ from django.contrib.gis.geos import GEOSGeometry, MultiPolygon
from django.contrib.gis.gdal.error import GDALException
from django.contrib.gis.geos.error import GEOSException
from django.core.cache import cache
+from django.core.serializers import serialize
from django.core.urlresolvers import reverse
from django.db.models.fields import BooleanField, IntegerField, FloatField, \
CharField, FieldDoesNotExist
@@ -153,6 +155,51 @@ def export_as_csv_action(description=_(u"Export selected as CSV file"),
return export_as_csv
+def export_as_geojson_action(
+ geometry_field, description=_("Export selected as GeoJSON file"),
+ fields=None, exclude=None):
+ """
+ This function returns an export GeoJSON action
+ 'fields' work like in django ModelForm
+ """
+ def export_as_geojson(modeladmin, request, queryset):
+ """
+ Generic zipped geojson export admin action.
+ """
+ opts = modeladmin.model._meta
+ field_names = set([field.name for field in opts.fields if
+ field.name != geometry_field])
+ if fields:
+ fieldset = set(fields)
+ field_names = field_names & fieldset
+ if exclude:
+ excludeset = set(exclude)
+ field_names = field_names - excludeset
+
+ basename = str(opts).replace('.', '_')
+
+ geojson = serialize(
+ 'geojson', queryset.order_by('pk'), geometry_field=geometry_field,
+ fields=field_names).encode("utf-8")
+ in_memory = StringIO()
+ zip = zipfile.ZipFile(in_memory, "a")
+ zip.writestr(basename + ".geojson", geojson)
+
+ # fix for Linux zip files read in Windows
+ for file in zip.filelist:
+ file.create_system = 0
+ zip.close()
+ response = HttpResponse(content_type='application/zip')
+ response['Content-Disposition'] = 'attachment; filename={}.zip'.format(
+ basename
+ )
+ in_memory.seek(0)
+ response.write(in_memory.read())
+ return response
+ export_as_geojson.short_description = description
+ return export_as_geojson
+
+
class HistorizedObjectAdmin(admin.ModelAdmin):
readonly_fields = ['history_creator', 'history_modifier', 'search_vector']
@@ -410,16 +457,19 @@ class ImportGeoJsonForm(forms.Form):
label=_(u"Prefix for numero INSEE"), max_length=20, required=False)
numero_insee_name = forms.CharField(
label=_(u"Field name for numero INSEE"), max_length=200,
- initial='code_insee')
+ initial='numero_insee')
name_name = forms.CharField(
- label=_(u"Field name for name"), max_length=200, initial='nom')
+ label=_(u"Field name for name"), max_length=200, initial='name')
UNIT_CHOICES = (('1', _(u"m2")), ('1000', _(u"km2")))
surface_unit = forms.ChoiceField(
label=_(u"Surface unit"), choices=UNIT_CHOICES)
surface_name = forms.CharField(
label=_(u"Field name for surface"), max_length=200, required=False)
year_name = forms.CharField(
- label=_(u"Field name for year"), max_length=200, required=False
+ label=_(u"Field name for year"), max_length=200, required=False,
+ initial="year",
+ help_text=_(u"Not required for new town. Leave it empty when not "
+ u"available.")
)
update = forms.BooleanField(
label=_(u"Update only geometry of existing towns"), required=False,
@@ -598,8 +648,8 @@ class ImportGEOJSONActionAdmin(object):
else:
modified = False
for k in values:
- if not keys['update'] and k not in ["center",
- "limit"]:
+ if keys['update'] and k not in ["center",
+ "limit"]:
continue
if values[k] != getattr(t, k):
setattr(t, k, values[k])
@@ -670,7 +720,9 @@ class TownAdmin(ImportGEOJSONActionAdmin, ImportActionAdmin):
list_filter = ("areas",)
form = AdminTownForm
inlines = [TownParentInline]
- actions = [export_as_csv_action(exclude=['center', 'limit'])]
+ actions = [export_as_csv_action(exclude=['center', 'limit']),
+ export_as_geojson_action(
+ "limit", exclude=["center", "departement", "cached_label"])]
import_keys = ['slug', 'txt_idx', 'numero_insee']