django-leaflet-storage / leaflet_storage / views.py

  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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
# -*- coding:utf-8 -*-


from django.conf import settings
from django.db import transaction
from django.contrib import messages
from django.utils import simplejson
from django.views.generic import View
from django.core.signing import Signer, BadSignature
from django.template import RequestContext
from django.contrib.auth.models import User
from django.views.generic import DetailView
from django.shortcuts import get_object_or_404
from django.contrib.gis.geos import GEOSGeometry
from django.core.urlresolvers import reverse_lazy
from django.utils.translation import ugettext as _
from django.views.generic.list import BaseListView, ListView
from django.contrib.auth import logout as do_logout
from django.template.loader import render_to_string
from django.views.generic.detail import BaseDetailView
from django.views.generic.base import TemplateView, RedirectView
from django.views.generic.edit import CreateView, UpdateView, FormView, DeleteView
from django.http import HttpResponse, HttpResponseForbidden, Http404, HttpResponseRedirect

from vectorformats.formats import django, geojson

from .models import (Map, Marker, DataLayer, Polyline, TileLayer,
                     Polygon, Pictogram)
from .utils import get_uri_template, smart_decode
from .forms import (QuickMapCreateForm, UpdateMapExtentForm, DataLayerForm,
                    UploadDataForm, UpdateMapPermissionsForm, MapSettingsForm,
                    MarkerForm, PolygonForm, PolylineForm, AnonymousMapPermissionsForm,
                    DownloadDataForm, UpdateMapTileLayerForm)


# ############## #
#     Utils      #
# ############## #

def _urls_for_js(urls=None):
    """
    Return templated URLs prepared for javascript.
    """
    if urls is None:
        # prevent circular import
        from .urls import urlpatterns
        urls = [url.name for url in urlpatterns if getattr(url, 'name', None)]
    return dict(zip(urls, [get_uri_template(url) for url in urls]))


def render_to_json(templates, response_kwargs, context, request):
    """
    Generate a JSON HttpResponse with rendered template HTML.
    """
    html = render_to_string(
        templates,
        response_kwargs,
        RequestContext(request, context)
    )
    _json = simplejson.dumps({
        "html": html
    })
    return HttpResponse(_json)


def simple_json_response(**kwargs):
    return HttpResponse(simplejson.dumps(kwargs))


# ############## #
#      Map       #
# ############## #

class GeoJSONMixin(object):

    geojson_fields = ['name', 'datalayer_id', 'options', 'icon']

    def geojson(self, context):
        qs = self.get_queryset()
        djf = django.Django(geodjango="latlng", properties=self.geojson_fields)
        geoj = geojson.GeoJSON()
        return geoj.encode(djf.decode(qs), to_string=False)


class MapView(DetailView):

    model = Map

    def get_int_from_request(self, key, fallback):
        try:
            output = int(self.request.GET[key])
        except (ValueError, KeyError):
            output = fallback
        return output

    def get_context_data(self, **kwargs):
        context = super(MapView, self).get_context_data(**kwargs)
        map_settings = {}
        datalayers = DataLayer.objects.filter(map=self.object)  # TODO manage state
        datalayer_data = [l.json for l in datalayers]
        map_settings['datalayers'] = datalayer_data
        map_settings['urls'] = _urls_for_js()
        map_settings['tilelayers'] = TileLayer.get_list(selected=self.object.get_tilelayer())
        map_settings['name'] = self.object.name
        map_settings['description'] = self.object.description
        if settings.USE_I18N:
            locale = settings.LANGUAGE_CODE
            # Check attr in case the middleware is not active
            if hasattr(self.request, "LANGUAGE_CODE"):
                locale = self.request.LANGUAGE_CODE
            map_settings['locale'] = locale
        if self.request.user.is_authenticated():
            allow_edit = int(self.object.can_edit(self.request.user, self.request))
        else:
            # Default to 1: display buttons for anonymous, they can
            # login from action process
            allow_edit = 1
        # Precedence to GET param
        allow_edit = self.get_int_from_request("allowEdit", allow_edit)
        map_settings['allowEdit'] = allow_edit
        for name, label, default in MapSettingsForm.SETTINGS:
            value = self.get_int_from_request(name, self.object.settings.get(name, default))
            try:
                value = int(value)
            except ValueError:
                value = default
            map_settings[name] = value
        map_settings["default_iconUrl"] = "%sstorage/src/img/marker.png" % settings.STATIC_URL
        map_settings['center'] = simplejson.loads(self.object.center.geojson)
        map_settings['storage_id'] = self.object.pk
        map_settings['zoom'] = self.object.zoom
        if map_settings['locateOnLoad']:
            map_settings['locate'] = {
                'setView': True,
                'enableHighAccuracy': True,
                'timeout': 3000
            }
        context['map_settings'] = simplejson.dumps(map_settings)
        return context


class MapInfos(DetailView):
    model = Map
    template_name = "leaflet_storage/map_infos.html"
    pk_url_kwarg = 'map_id'

    def render_to_response(self, context, **response_kwargs):
        return render_to_json(self.get_template_names(), response_kwargs, context, self.request)


class QuickMapCreate(CreateView):
    model = Map
    form_class = QuickMapCreateForm

    def form_valid(self, form):
        """
        Provide default values, to keep form simple.
        """
        if self.request.user.is_authenticated():
            form.instance.owner = self.request.user
        form.instance.tilelayer = TileLayer.get_default()
        self.object = form.save()
        DataLayer.create_default(self.object)
        response = simple_json_response(redirect=self.get_success_url())
        if not self.request.user.is_authenticated():
            key, value = self.object.signed_cookie_elements
            response.set_signed_cookie(key, value)
            anonymous_url = "%s%s" % (
                settings.SITE_URL,
                self.object.get_anonymous_edit_url()
            )
            msg = _(
                "Your map has been created! If you want to edit this map from "
                "another computer, please use this link: %(anonymous_url)s"
                % {"anonymous_url": anonymous_url}
            )
        else:
            msg = _("Congratulations, your map has been created! To start editing, click on the pen icon.")
        messages.info(self.request, msg)
        return response

    def render_to_response(self, context, **response_kwargs):
        return render_to_json(self.get_template_names(), response_kwargs, context, self.request)

    def get_context_data(self, **kwargs):
        kwargs.update({
            'action_url': reverse_lazy('map_add')
        })
        return super(QuickMapCreate, self).get_context_data(**kwargs)


# TODO: factorize with QuickCreate!
class QuickMapUpdate(UpdateView):
    model = Map
    form_class = QuickMapCreateForm
    pk_url_kwarg = 'map_id'

    def form_valid(self, form):
        self.object = form.save()
        return simple_json_response(redirect=self.get_success_url())

    def render_to_response(self, context, **response_kwargs):
        return render_to_json(self.get_template_names(), response_kwargs, context, self.request)

    def get_context_data(self, **kwargs):
        kwargs.update({
            'action_url': reverse_lazy('map_update', args=[self.object.pk]),
            'delete_url': reverse_lazy('map_delete', args=[self.object.pk]),
            'clone_url': reverse_lazy('map_clone', args=[self.object.pk]),
        })
        return super(QuickMapUpdate, self).get_context_data(**kwargs)


class UpdateMapExtent(UpdateView):
    model = Map
    form_class = UpdateMapExtentForm
    pk_url_kwarg = 'map_id'

    def form_invalid(self, form):
        return simple_json_response(info=form.errors)

    def form_valid(self, form):
        self.object = form.save()
        return simple_json_response(info=_("Zoom and center updated with success!"))


class UpdateMapTileLayer(UpdateView):
    model = Map
    form_class = UpdateMapTileLayerForm
    pk_url_kwarg = 'map_id'

    def form_invalid(self, form):
        return simple_json_response(info=form.errors)

    def form_valid(self, form):
        self.object = form.save()
        return simple_json_response(info=_("Map background updated with success!"))


class UpdateMapPermissions(UpdateView):
    template_name = "leaflet_storage/map_update_permissions.html"
    model = Map
    pk_url_kwarg = 'map_id'

    def get_form_class(self):
        if self.object.owner:
            return UpdateMapPermissionsForm
        else:
            return AnonymousMapPermissionsForm

    def get_form(self, form_class):
        form = super(UpdateMapPermissions, self).get_form(form_class)
        user = self.request.user
        if self.object.owner and not user == self.object.owner:
            del form.fields['edit_status']
        return form

    def form_valid(self, form):
        self.object = form.save()
        return simple_json_response(info=_("Map editors updated with success!"))

    def render_to_response(self, context, **response_kwargs):
        return render_to_json(self.get_template_names(), response_kwargs, context, self.request)


class UpdateMapSettings(UpdateView):
    template_name = "leaflet_storage/map_update_settings.html"
    model = Map
    form_class = MapSettingsForm
    pk_url_kwarg = 'map_id'

    def form_valid(self, form):
        self.object.settings = form.cleaned_data
        self.object.save()
        # We need to reload the page, to make the UI take into account the new
        # settings
        return simple_json_response(redirect=self.object.get_absolute_url())

    def render_to_response(self, context, **response_kwargs):
        return render_to_json(self.get_template_names(), response_kwargs, context, self.request)


class UploadData(FormView):
    template_name = "leaflet_storage/upload_form.html"
    form_class = UploadDataForm
    pk_url_kwarg = 'map_id'

    def get_form(self, form_class):
        form = super(UploadData, self).get_form(form_class)
        map_inst = self.kwargs['map_inst']
        form.fields['datalayer'].queryset = DataLayer.objects.filter(map=map_inst)
        return form

    def get_context_data(self, **kwargs):
        kwargs.update({
            'action_url': reverse_lazy('upload_data', kwargs={'map_id': self.kwargs['map_id']})
        })
        return super(UploadData, self).get_context_data(**kwargs)

    @transaction.commit_manually
    def form_valid(self, form):
        FEATURE_TO_MODEL = {
            'Point': Marker,
            'LineString': Polyline,
            'Polygon': Polygon
        }
        # Use a tuple to add more sources possible
        # first item is field name
        FIELDS = [
            ('name', 'title', ),
            ('description', 'desc', 'text', ),
            ('color', 'hexcolor', )
        ]
        features = (form.cleaned_data.get('data_file')
                   or form.cleaned_data.get('data_url')
                   or form.cleaned_data.get('data_raw'))
        datalayer = form.cleaned_data.get('datalayer')
        counter = 0
        for feature in features:
            sid = transaction.savepoint()
            klass = FEATURE_TO_MODEL.get(feature.geometry['type'], None)
            if not klass:
                continue  # TODO notify user
            # Remove altitude, if there
            try:
                if feature.geometry['type'] == "LineString":
                    feature.geometry['coordinates'] = map(
                        lambda x: x[:2],
                        feature.geometry['coordinates']
                    )
                elif feature.geometry['type'] == "Point":
                    feature.geometry['coordinates'] = feature.geometry['coordinates'][:2]
                elif feature.geometry['type'] == "Polygon":
                    feature.geometry['coordinates'] = map(
                        lambda x: map(lambda y: y[:2], x),
                        feature.geometry['coordinates']
                    )
            except Exception:
                continue
            try:
                latlng = GEOSGeometry(simplejson.dumps(feature.geometry))
            except Exception:
                continue  # TODO notify user
            if latlng.empty:
                continue  # TODO notify user
            kwargs = {
                'latlng': latlng,
                'datalayer': datalayer,
                'name': datalayer.name  # Default
            }
            for field in FIELDS:
                if isinstance(field, tuple):
                    name = field[0]
                    candidates = field
                else:
                    name = field
                    candidates = [field]
                for candidate in candidates:
                    if candidate in feature.properties:
                        value = feature.properties[candidate]
                        if not value:
                            continue
                        value = smart_decode(value)
                        if name in klass._meta.get_all_field_names():
                            kwargs[name] = value
                        else:
                            # it's an option
                            if not "options" in kwargs:
                                kwargs['options'] = {}
                            kwargs['options'][name] = value
                        break
            try:
                klass.objects.create(**kwargs)
            except Exception:
                transaction.savepoint_rollback(sid)
                continue  # TODO notify user
            else:
                transaction.savepoint_commit(sid)
            counter += 1
        transaction.commit()
        if counter:
            kwargs = {
                'datalayer': datalayer.json,
                'info': _("%d features created!") % counter,
            }
        else:
            kwargs = {
                'error': _("No valid feature has been found :("),
            }
        return simple_json_response(**kwargs)

    def render_to_response(self, context, **response_kwargs):
        return render_to_json(self.get_template_names(), response_kwargs, context, self.request)


class DownloadData(GeoJSONMixin, DetailView):

    model = Map
    pk_url_kwarg = 'map_id'
    geojson_fields = ['name', 'datalayer_id', 'options', 'icon', 'description', 'color']

    def get_queryset(self):
        features = []
        for datalayer in self.object.datalayer_set.all():
            features += datalayer.features
        return features

    def get_object(self):
        return get_object_or_404(Map, pk=self.kwargs[self.pk_url_kwarg])

    def render_to_response(self, context):
        response = simple_json_response(**self.geojson(context))
        response['Content-Type'] = "application/json"
        response['Content-Disposition'] = 'attachment; filename="features.json"'
        return response


class EmbedMap(DetailView):
    model = Map
    template_name = "leaflet_storage/map_embed.html"
    pk_url_kwarg = 'map_id'

    def get_context_data(self, **kwargs):
        site_url = (settings.SHORT_SITE_URL if hasattr(settings, 'SHORT_SITE_URL')
                   else settings.SITE_URL if hasattr(settings, 'SITE_URL')
                   else 'http://%s' % self.request.META['HTTP_HOST'])
        iframe_url = map_url = '%s%s' % (site_url, self.object.get_absolute_url())
        qs_kwargs = {
            'allowEdit': 0,
            'embedControl': 0,
            'homeControl': 0,
            'locateControl': 0,
            'jumpToLocationControl': 0,
            'editInOSMControl': 0,
            'scaleControl': 0,
            'miniMap': 0,
            'tileLayersControl': 0,
            'scrollWheelZoom': 0,
        }
        query_string = "&".join("%s=%s" % (k, v) for k, v in qs_kwargs.iteritems())
        iframe_url = "%s?%s" % (iframe_url, query_string)
        short_url_name = getattr(settings, 'MAP_SHORT_URL_NAME', 'map_short_url')
        map_short_url = "%s%s" % (site_url, reverse_lazy(short_url_name, kwargs={'pk': self.object.pk}))
        kwargs.update({
            'map_url': map_url,
            'iframe_url': iframe_url,
            'map_short_url': map_short_url,
            'download_form': DownloadDataForm()
        })
        return super(EmbedMap, self).get_context_data(**kwargs)

    def render_to_response(self, context, **response_kwargs):
        return render_to_json(self.get_template_names(), response_kwargs, context, self.request)


class MapDelete(DeleteView):
    model = Map
    pk_url_kwarg = "map_id"

    def render_to_response(self, context, **response_kwargs):
        return render_to_json(self.get_template_names(), response_kwargs, context, self.request)

    def delete(self, *args, **kwargs):
        self.object = self.get_object()
        if not self.request.user == self.object.owner:
            return HttpResponseForbidden(_('Only its owner can delete the map.'))
        self.object.delete()
        return simple_json_response(redirect="/")

    def get_context_data(self, **kwargs):
        kwargs.update({
            'action_url': reverse_lazy('map_delete', kwargs={'map_id': self.kwargs['map_id']})
        })
        return super(MapDelete, self).get_context_data(**kwargs)


class MapClone(View):

    def get(self, *args, **kwargs):
        if not getattr(settings, "LEAFLET_STORAGE_ALLOW_ANONYMOUS", False) \
           and not self.request.user.is_authenticated():
            return HttpResponseForbidden('Forbidden')
        owner = self.request.user if self.request.user.is_authenticated() else None
        self.object = kwargs['map_inst'].clone(owner=owner)
        response = simple_json_response(redirect=self.object.get_absolute_url())
        if not self.request.user.is_authenticated():
            key, value = self.object.signed_cookie_elements
            response.set_signed_cookie(key, value)
            anonymous_url = "%s%s" % (
                settings.SITE_URL,
                self.object.get_anonymous_edit_url()
            )
            msg = _(
                "Your map has been cloned! If you want to edit this map from "
                "another computer, please use this link: %(anonymous_url)s"
                % {"anonymous_url": anonymous_url}
            )
        else:
            msg = _("Congratulations, your map has been cloned!")
        messages.info(self.request, msg)
        return response


class MapShortUrl(RedirectView):
    query_string = True

    def get_redirect_url(self, **kwargs):
        map_inst = get_object_or_404(Map, pk=kwargs['pk'])
        url = map_inst.get_absolute_url()
        if self.query_string:
            args = self.request.META.get('QUERY_STRING', '')
            if args:
                url = "%s?%s" % (url, args)
        return url


class MapOldUrl(RedirectView):
    """
    Handle map URLs from before anonymous allowing.
    """
    query_string = True

    def get_redirect_url(self, **kwargs):
        owner = get_object_or_404(User, username=self.kwargs['username'])
        map_inst = get_object_or_404(Map, slug=self.kwargs['slug'], owner=owner)
        url = map_inst.get_absolute_url()
        if self.query_string:
            args = self.request.META.get('QUERY_STRING', '')
            if args:
                url = "%s?%s" % (url, args)
        return url


class MapAnonymousEditUrl(RedirectView):

    def get(self, request, *args, **kwargs):
        signer = Signer()
        try:
            pk = signer.unsign(self.kwargs['signature'])
        except BadSignature:
            return HttpResponseForbidden('Bad Signature')
        else:
            map_inst = get_object_or_404(Map, pk=pk)
            url = map_inst.get_absolute_url()
            response = HttpResponseRedirect(url)
            if not map_inst.owner:
                key, value = map_inst.signed_cookie_elements
                response.set_signed_cookie(key, value)
            return response


# ############## #
#    Features    #
# ############## #


class FeatureGeoJSONListView(BaseListView, GeoJSONMixin):

    def get_queryset(self):
        datalayer = get_object_or_404(DataLayer, pk=self.kwargs['datalayer_id'])
        return datalayer.features

    def render_to_response(self, context, **response_kwargs):
        geoj = self.geojson(context)
        return HttpResponse(simplejson.dumps(geoj))


class FeatureView(DetailView):
    context_object_name = "feature"

    def render_to_response(self, context, **response_kwargs):
        return render_to_json(self.get_template_names(), response_kwargs, context, self.request)

    def get_template_names(self):
        """
        Add a fallback, but keep the default templates to make it easily
        extendable.
        """
        templates = super(FeatureView, self).get_template_names()
        templates.append("leaflet_storage/feature_detail.html")
        return templates


class FeatureAdd(CreateView):

    def get_success_url(self):
        return reverse_lazy(self.geojson_url, kwargs={"pk": self.object.pk})

    def render_to_response(self, context, **response_kwargs):
        return render_to_json(self.get_template_names(), response_kwargs, context, self.request)

    def get_form(self, form_class):
        form = super(FeatureAdd, self).get_form(form_class)
        map_inst = self.kwargs['map_inst']
        layers = DataLayer.objects.filter(map=map_inst)
        form.fields['datalayer'].queryset = layers
        if layers:
            form.fields['datalayer'].initial = layers[0]
        return form

    def get_template_names(self):
        """
        Add a fallback, but keep the default templates to make it easily
        extendable.
        """
        templates = super(FeatureAdd, self).get_template_names()
        templates.append("leaflet_storage/feature_form.html")
        return templates


class FeatureUpdate(UpdateView):

    def get_success_url(self):
        return reverse_lazy(self.geojson_url, kwargs={"pk": self.object.pk})

    def render_to_response(self, context, **response_kwargs):
        return render_to_json(self.get_template_names(), response_kwargs, context, self.request)

    def get_context_data(self, **kwargs):
        kwargs.update({
            'delete_url': reverse_lazy(self.delete_url, kwargs={'map_id': self.kwargs['map_id'], 'pk': self.object.pk})
        })
        return super(FeatureUpdate, self).get_context_data(**kwargs)

    # TODO: factorize with FeatureAdd!
    def get_form(self, form_class):
        form = super(FeatureUpdate, self).get_form(form_class)
        map_inst = self.kwargs['map_inst']
        form.fields['datalayer'].queryset = DataLayer.objects.filter(map=map_inst)
        return form

    def get_template_names(self):
        """
        Add a fallback, but keep the default templates to make it easily
        extendable.
        """
        templates = super(FeatureUpdate, self).get_template_names()
        templates.append("leaflet_storage/feature_form.html")
        return templates


class FeatureDelete(DeleteView):
    context_object_name = "feature"
    template_name = "leaflet_storage/feature_confirm_delete.html"

    def render_to_response(self, context, **response_kwargs):
        return render_to_json(self.get_template_names(), response_kwargs, context, self.request)

    def delete(self, *args, **kwargs):
        self.object = self.get_object()
        self.object.delete()
        return simple_json_response(
            #Translators: "feature" is a feature type: Marker, Polyline, Polygon
            info=_("%(feature)s successfully deleted." % {"feature": self.model._meta.verbose_name})
        )


class FeatureGeoJSON(BaseDetailView, GeoJSONMixin):

    def get_queryset(self):
        return self.model.objects.filter(pk=self.kwargs['pk'])

    def render_to_response(self, context):
        collection = self.geojson(context)
        try:
            geoj = collection['features'][0]
        except KeyError:
            return Http404()
        return HttpResponse(simplejson.dumps(geoj))


class MarkerGeoJSON(FeatureGeoJSON):
    model = Marker


class MarkerDelete(FeatureDelete):
    model = Marker


class MarkerView(FeatureView):
    model = Marker


class MarkerUpdate(FeatureUpdate):
    model = Marker
    geojson_url = 'marker_geojson'
    delete_url = "marker_delete"
    form_class = MarkerForm


class MarkerAdd(FeatureAdd):
    model = Marker
    geojson_url = 'marker_geojson'
    form_class = MarkerForm


class PolylineView(FeatureView):
    model = Polyline


class PolylineAdd(FeatureAdd):
    model = Polyline
    geojson_url = 'polyline_geojson'
    form_class = PolylineForm


class PolylineUpdate(FeatureUpdate):
    model = Polyline
    geojson_url = 'polyline_geojson'
    delete_url = "polyline_delete"
    form_class = PolylineForm


class PolylineDelete(FeatureDelete):
    model = Polyline


class PolylineGeoJSON(FeatureGeoJSON):
    model = Polyline


class PolygonView(FeatureView):
    model = Polygon


class PolygonAdd(FeatureAdd):
    model = Polygon
    geojson_url = 'polygon_geojson'
    form_class = PolygonForm


class PolygonUpdate(FeatureUpdate):
    model = Polygon
    geojson_url = 'polygon_geojson'
    delete_url = "polygon_delete"
    form_class = PolygonForm


class PolygonDelete(FeatureDelete):
    model = Polygon


class PolygonGeoJSON(FeatureGeoJSON):
    model = Polygon


# ############## #
#    DataLayer   #
# ############## #

class DataLayerCreate(CreateView):
    model = DataLayer
    form_class = DataLayerForm

    def render_to_response(self, context, **response_kwargs):
        return render_to_json(self.get_template_names(), response_kwargs, context, self.request)

    def get_context_data(self, **kwargs):
        kwargs.update({
            'action_url': reverse_lazy('datalayer_add', kwargs={'map_id': self.kwargs['map_id']})
        })
        return super(DataLayerCreate, self).get_context_data(**kwargs)

    def get_initial(self):
        initial = super(DataLayerCreate, self).get_initial()
        map_inst = self.kwargs['map_inst']
        initial.update({
            "map": map_inst
        })
        return initial

    def form_valid(self, form):
        self.object = form.save()
        return simple_json_response(datalayer=self.object.json)


class DataLayerUpdate(UpdateView):
    model = DataLayer
    form_class = DataLayerForm

    def render_to_response(self, context, **response_kwargs):
        return render_to_json(self.get_template_names(), response_kwargs, context, self.request)

    def get_context_data(self, **kwargs):
        kwargs.update({
            'action_url': reverse_lazy('datalayer_update', kwargs={'map_id': self.kwargs['map_id'], 'pk': self.object.pk}),
            'delete_url': reverse_lazy('datalayer_delete', kwargs={'map_id': self.kwargs['map_id'], 'pk': self.object.pk})
        })
        return super(DataLayerUpdate, self).get_context_data(**kwargs)

    def form_valid(self, form):
        self.object = form.save()
        return simple_json_response(datalayer=self.object.json)


class DataLayerDelete(DeleteView):
    model = DataLayer

    def render_to_response(self, context, **response_kwargs):
        return render_to_json(self.get_template_names(), response_kwargs, context, self.request)

    def delete(self, *args, **kwargs):
        self.object = self.get_object()
        self.object.delete()
        return simple_json_response(info=_("Layer successfully deleted."))


# ############## #
#     Picto      #
# ############## #

class PictogramJSONList(ListView):
    model = Pictogram

    def render_to_response(self, context, **response_kwargs):
        content = [p.json for p in Pictogram.objects.all()]
        return simple_json_response(pictogram_list=content)


# ############## #
#     Generic    #
# ############## #

def logout(request):
    do_logout(request)
    return simple_json_response(redirect="/")


class LoginPopupEnd(TemplateView):
    """
    End of a loggin process in popup.
    Basically close the popup.
    """
    template_name = "leaflet_storage/login_popup_end.html"
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.