Debian Codegraph @

django/contrib/gis/sitemaps/views.py

raw
1 from django.apps import apps
2 from django.contrib.gis.db.models import GeometryField
3 from django.contrib.gis.db.models.functions import AsKML, Transform
4 from django.contrib.gis.shortcuts import render_to_kml, render_to_kmz
5 from django.core.exceptions import FieldDoesNotExist
6 from django.db import DEFAULT_DB_ALIAS, connections
7 from django.http import Http404
8
9
10 def kml(request, label, model, field_name=None, compress=False, using=DEFAULT_DB_ALIAS):
11 """
12 This view generates KML for the given app label, model, and field name.
13
14 The field name must be that of a geographic field.
15 """
16 placemarks = []
17 try:
18 klass = apps.get_model(label, model)
19 except LookupError:
20 raise Http404(
21 'You must supply a valid app label and module name. Got "%s.%s"'
22 % (label, model)
23 )
24
25 if field_name:
26 try:
27 field = klass._meta.get_field(field_name)
28 if not isinstance(field, GeometryField):
29 raise FieldDoesNotExist
30 except FieldDoesNotExist:
31 raise Http404("Invalid geometry field.")
32
33 connection = connections[using]
34
35 if connection.features.has_AsKML_function:
36 # Database will take care of transformation.
37 placemarks = klass._default_manager.using(using).annotate(kml=AsKML(field_name))
38 else:
39 # If the database offers no KML method, we use the `kml`
40 # attribute of the lazy geometry instead.
41 placemarks = []
42 if connection.features.has_Transform_function:
43 qs = klass._default_manager.using(using).annotate(
44 **{"%s_4326" % field_name: Transform(field_name, 4326)}
45 )
46 field_name += "_4326"
47 else:
48 qs = klass._default_manager.using(using).all()
49 for mod in qs:
50 mod.kml = getattr(mod, field_name).kml
51 placemarks.append(mod)
52
53 # Getting the render function and rendering to the correct.
54 if compress:
55 render = render_to_kmz
56 else:
57 render = render_to_kml
58 return render("gis/kml/placemarks.kml", {"places": placemarks})
59
60
61 def kmz(request, label, model, field_name=None, using=DEFAULT_DB_ALIAS):
62 """
63 Return KMZ for the given app label, model, and field name.
64 """
65 return kml(request, label, model, field_name, compress=True, using=using)