def kml_export_data(id_string, user, xform=None): """ KML export data from form submissions. """ def cached_get_labels(xpath): """ Get and Cache labels for the XForm. """ if xpath in list(labels): return labels[xpath] labels[xpath] = xform.get_label(xpath) return labels[xpath] xform = xform or XForm.objects.get(id_string=id_string, user=user) data_kwargs = {'geom__isnull': False} if xform.is_merged_dataset: data_kwargs.update({ 'xform_id__in': [i for i in xform.mergedxform.xforms.filter( deleted_at__isnull=True).values_list('id', flat=True)] }) else: data_kwargs.update({'xform_id': xform.pk}) instances = Instance.objects.filter(**data_kwargs).order_by('id') data_for_template = [] labels = {} for instance in queryset_iterator(instances): # read the survey instances data_for_display = instance.get_dict() xpaths = list(data_for_display) xpaths.sort(key=cmp_to_key(instance.xform.get_xpath_cmp())) table_rows = [ '<tr><td>%s</td><td>%s</td></tr>' % (cached_get_labels(xpath), data_for_display[xpath]) for xpath in xpaths if not xpath.startswith(u"_")] img_urls = image_urls(instance) if instance.point: data_for_template.append({ 'name': instance.xform.id_string, 'id': instance.id, 'lat': instance.point.y, 'lng': instance.point.x, 'image_urls': img_urls, 'table': '<table border="1"><a href="#"><img width="210" ' 'class="thumbnail" src="%s" alt=""></a>%s' '</table>' % (img_urls[0] if img_urls else "", ''.join(table_rows))}) return data_for_template