combo-plugin-gnm/combo_plugin_gnm/management/commands/gnm_create_places.py

79 lines
3.4 KiB
Python

# combo-plugin-gnm - Combo GNM plugin
# Copyright (C) 2017 Entr'ouvert
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero 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 Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
from combo.apps.maps.models import MapLayer
from combo.data.models import ConfigJsonCell, Page
from django.conf import settings
from django.core.management.base import BaseCommand
from django.template import Context, Template
class Command(BaseCommand):
def handle(self, *args, **options):
verbosity = options.get('verbosity')
places_page = Page.objects.get(slug='lieux')
for layer in MapLayer.objects.all():
json_cell_type = settings.JSON_CELL_TYPES.get(layer.slug)
if not json_cell_type or not json_cell_type.get('toodego:page'):
continue
cell_form_keys = [x['varname'] for x in json_cell_type.get('form')]
parent_page, created = Page.objects.get_or_create(
parent__id=places_page.id,
slug=layer.slug,
defaults={
'title': layer.label,
'redirect_url': '..',
'parent': places_page,
},
)
parent_page.title = layer.label
parent_page.save()
layer.properties = None # get all properties
resp = layer.get_geojson(request=None)
if isinstance(resp['features'], dict) and resp['features'].get('err'):
if verbosity:
self.stderr.write('error in layer %s: %r\n' % (layer, resp['features']))
continue
for feature in resp['features']:
cell_parameters = {
x: feature['properties'][x] for x in feature['properties'] if x in cell_form_keys
}
try:
cell = ConfigJsonCell.objects.get(
key=layer.slug, parameters=cell_parameters, page__template_name='place'
)
except ConfigJsonCell.DoesNotExist:
page = Page()
page_title_template = json_cell_type.get(
'toodego:page-title-template', '{{ properties.nom|safe }}'
)
ctx = Context({'properties': feature['properties']})
page.title = Template(page_title_template).render(ctx)
if not page.title:
continue
page.parent = Page.objects.get(slug=layer.slug, parent__isnull=False)
page.template_name = 'place'
page.save()
cell = ConfigJsonCell()
cell.order = 0
cell.placeholder = 'content'
cell.key = layer.slug
cell.parameters = cell_parameters
cell.page = page
cell.save()