You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. from django.apps import apps
  2. from django.contrib.gis.db.models.fields import GeometryField
  3. from django.contrib.sitemaps import Sitemap
  4. from django.db import models
  5. from django.urls import reverse
  6. class KMLSitemap(Sitemap):
  7. """
  8. A minimal hook to produce KML sitemaps.
  9. """
  10. geo_format = 'kml'
  11. def __init__(self, locations=None):
  12. # If no locations specified, then we try to build for
  13. # every model in installed applications.
  14. self.locations = self._build_kml_sources(locations)
  15. def _build_kml_sources(self, sources):
  16. """
  17. Go through the given sources and return a 3-tuple of the application
  18. label, module name, and field name of every GeometryField encountered
  19. in the sources.
  20. If no sources are provided, then all models.
  21. """
  22. kml_sources = []
  23. if sources is None:
  24. sources = apps.get_models()
  25. for source in sources:
  26. if isinstance(source, models.base.ModelBase):
  27. for field in source._meta.fields:
  28. if isinstance(field, GeometryField):
  29. kml_sources.append((source._meta.app_label,
  30. source._meta.model_name,
  31. field.name))
  32. elif isinstance(source, (list, tuple)):
  33. if len(source) != 3:
  34. raise ValueError('Must specify a 3-tuple of (app_label, module_name, field_name).')
  35. kml_sources.append(source)
  36. else:
  37. raise TypeError('KML Sources must be a model or a 3-tuple.')
  38. return kml_sources
  39. def get_urls(self, page=1, site=None, protocol=None):
  40. """
  41. This method is overridden so the appropriate `geo_format` attribute
  42. is placed on each URL element.
  43. """
  44. urls = Sitemap.get_urls(self, page=page, site=site, protocol=protocol)
  45. for url in urls:
  46. url['geo_format'] = self.geo_format
  47. return urls
  48. def items(self):
  49. return self.locations
  50. def location(self, obj):
  51. return reverse(
  52. 'django.contrib.gis.sitemaps.views.%s' % self.geo_format,
  53. kwargs={
  54. 'label': obj[0],
  55. 'model': obj[1],
  56. 'field_name': obj[2],
  57. },
  58. )
  59. class KMZSitemap(KMLSitemap):
  60. geo_format = 'kmz'