def _format_results(res): result = [] for obj in res: id = obj['object_id'] model = get_model_from_table_ref(obj['table_ref']) try: db_object = model.objects.get(pk=id) model_name = db_object.__class__.__name__.lower() hashlink = '{}{}'.format(model_name[0], id) link = db_object.view_url result.append({ 'id': id, 'name': obj['name'], 'link': link, 'hashlink': hashlink, 'model': model_name, 'disabled': 'disabled' if not _has_geojson(db_object) else '', 'geojson': create_geojson([db_object]), }) except: # object not on DB pass return result
def edit_organization(request, id='', *arg, **kwargs): organization = get_object_or_None(Organization, pk=id) or Organization() geojson = create_geojson([organization], convert=False) if geojson and geojson.get('features'): geojson['features'][0]['properties']['userCanEdit'] = True geojson = json.dumps(geojson) def on_get(request, form): form = FormOrganizationGeoRef(instance=organization) form.helper.form_action = reverse('edit_organization', kwargs={'id': organization.id}) return form def on_after_save(request, obj): return { 'redirect': reverse('view_organization', kwargs={'id': obj.id}) } return { 'on_get': on_get, 'on_after_save': on_after_save, 'geojson': geojson, 'organization': organization }
def geojson(self): items = [] for ro in self.related_objects: obj = ro.content_object if obj and not obj.is_empty(): items.append(obj) return create_geojson(items)
def view(request, id): community = get_object_or_404(Community, pk=id) geojson = create_geojson([community]) photos = paginated_query(UploadedFile.get_files_for(community), request, size=3) return dict(community=community, geojson=geojson, photos=photos)
def profile(request, id=''): logger.debug('id : {}'.format(id)) if not id: if request.user.is_authenticated(): user = request.user else: return redirect(reverse('user_login')) else: user = get_object_or_404(User, id=id) geojson = create_geojson([user], convert=False, discard_empty=True) if geojson: geojson['features'][0]['properties']['image'] = '/static/img/user.png' geojson = to_json(geojson) filters = request.GET.get('filters', []) if filters: filters = filters.split(',') if filters: query_set = Update.objects.filter(object_type__in=filters) else: query_set = Update.objects.all() reg = r'[^0-9]%d[^0-9]' % user.id query_set = query_set.filter(_user_ids__regex=reg).order_by('-date') updates_page = paginated_query(query_set, request, size=10) return dict(user_profile=user, geojson=geojson, updates_page=updates_page)
def show(request, id=None): resource = get_object_or_404(Resource, pk=id) geojson = create_geojson([resource]) similar = Resource.objects.filter(Q(kind=resource.kind) | Q(tags__in=resource.tags.all())).exclude(pk=resource.id).distinct()[:5] return dict(resource=resource, similar=similar, geojson=geojson)
def profile_update(request): signatures = [] for sig in Signature.objects.filter(user=request.user): try: ct = ContentType.objects.get_for_id(sig.content_type_id) obj = ct.get_object_for_this_type(pk=sig.object_id) signatures.append({ 'signature_id': sig.id, 'obj_name': getattr(obj, 'name', '') or getattr( obj, 'title', ''), 'obj_id': obj.id, 'model_name': ct.name, 'app_name': ct.app_label, 'permalink': obj.view_url, 'has_geojson': not 'EMPTY' in getattr( obj, 'geometry', 'EMPTY'), }) except: # signature for an object that cannot be found (probably deleted) sig.delete() digest_obj = DigestSignature.objects.filter(user=request.user) digest = digest_obj[0].digest_type if digest_obj.count() \ else 'N' form_profile = FormProfile(instance=request.user) geojson = create_geojson([request.user], convert=False) geojson['features'][0]['properties']['image'] = '/static/img/me.png' geojson = to_json(geojson) return dict(signatures=signatures, form_profile=form_profile, digest=digest, geojson=geojson)
def profile(request, id=''): logger.debug('id : {}'.format(id)) if not id: if request.user.is_authenticated(): user = request.user else: return redirect(reverse('user_login')) else: user = get_object_or_404(User, id=id) geojson = create_geojson([user], convert=False, discard_empty=True) if geojson: geojson['features'][0]['properties']['image'] = '/static/img/user.png' geojson = json.dumps(geojson) filters = request.GET.get('filters', []) if filters: filters = filters.split(',') if filters: query_set = Update.objects.filter(object_type__in=filters) else: query_set = Update.objects.all() reg = r'[^0-9]%d[^0-9]' % user.id query_set = query_set.filter(_user_ids__regex=reg).order_by('-date') updates_page = paginated_query(query_set, request, size=10) return dict(user_profile=user, geojson=geojson, updates_page=updates_page)
def needs_geojson(request): bounds = request.GET.get('bounds', None) x1, y2, x2, y1 = [float(i) for i in bounds.split(',')] polygon = Polygon(((x1, y1), (x1, y2), (x2, y2), (x2, y1), (x1, y1))) needs = Need.objects.filter( Q(points__intersects=polygon) | Q(lines__intersects=polygon) | Q(polys__intersects=polygon)) geojson = create_geojson(needs) return HttpResponse(to_json(geojson), mimetype="application/x-javascript")
def get_geojson_from_hashlink(request): hashlink = request.GET.get('hashlink', '') if hashlink: obj = ENTITY_MODEL[hashlink[0]].objects.get(pk=hashlink[1:]) geojson = create_geojson([obj]) else: geojson = {} return {'geojson': geojson}
def show(request, id=''): organization = get_object_or_404(Organization, pk=id) geojson = create_geojson([organization]) files = UploadedFile.get_files_for(organization) if organization.logo_id: files = files.exclude(pk=organization.logo_id) return dict(organization=organization, geojson=geojson)
def show(request, id=""): organization = get_object_or_None(Organization, pk=id) or Organization() geojson = create_geojson([organization]) files = UploadedFile.get_files_for(organization) if organization.logo_id: files = files.exclude(pk=organization.logo_id) return dict(organization=organization, geojson=geojson)
def show(request, id=''): organization = get_object_or_None(Organization, pk=id) or Organization() branches = organization.organizationbranch_set.all().order_by('name') geojson = create_geojson(branches) files = UploadedFile.get_files_for(organization) if organization.logo_id: files = files.exclude(pk=organization.logo_id) return dict(organization=organization, geojson=geojson)
def communities_geojson(request): bounds = request.GET.get('bounds', None) x1, y2, x2, y1 = [float(i) for i in bounds.split(',')] polygon = Polygon(((x1, y1), (x1, y2), (x2, y2), (x2, y1), (x1, y1))) # communities = Community.objects.filter(geometry__intersects=polygon) intersects_polygon = (Q(points__intersects=polygon) | Q(lines__intersects=polygon) | Q(polys__intersects=polygon)) communities = Community.objects.filter(intersects_polygon) geojson = create_geojson(communities) return HttpResponse(to_json(geojson), mimetype="application/x-javascript")
def get_geojson_from_hashlink(request): """View that returns geojson using the permalink hash code to identify the correct object.""" hashlink = request.GET.get('hashlink', '') if hashlink: obj = ENTITY_MODEL[hashlink[0]].objects.get(pk=hashlink[1:]) geojson = create_geojson([obj]) else: geojson = {} return {'geojson': geojson}
def needs_geojson(request): bounds = request.GET.get('bounds', None) x1, y2, x2, y1 = [float(i) for i in bounds.split(',')] polygon = Polygon(((x1, y1), (x1, y2), (x2, y2), (x2, y1), (x1, y1))) needs = Need.objects.filter( Q(points__intersects=polygon) | Q(lines__intersects=polygon) | Q(polys__intersects=polygon) ) geojson = create_geojson(needs) return HttpResponse(to_json(geojson), mimetype="application/x-javascript")
def project_view(request, id=''): project = get_object_or_404(Project, pk=id) proj_objects, items = {}, [] proj_objects['User'] = {'app_name': 'authentication', 'objects_list': []} for c in project.all_contributors: proj_objects['User']['objects_list'].append({ 'name': c.name, 'link': c.view_url, 'avatar': c.avatar, 'id': c.id, 'has_geojson': bool(getattr(c, 'geometry', '')) }) for p in project.related_objects: obj = p.content_object if obj: if not proj_objects.get(obj.__class__.__name__, None): proj_objects[obj.__class__.__name__] = { 'app_name': obj.__module__.split('.')[0], 'objects_list': [] } proj_objects[obj.__class__.__name__]['objects_list'].append({ 'name': obj.name.strip(), 'link': obj.view_url, 'id': obj.id, 'has_geojson': bool(getattr(obj, 'geometry', '')) }) if not obj.is_empty(): items.append(obj) geojson = create_geojson(items) # ugly sort for key in proj_objects.iterkeys(): proj_objects[key]['objects_list'].sort(key=lambda o: o['name']) return dict(project=project, geojson=geojson, proj_objects=proj_objects, user_can_discuss=project.user_can_discuss(request.user))
def project_map(request, id=''): project = get_object_or_404(Project, pk=id) related_items = [] for obj in project.related_items: if obj and not obj.is_empty(): related_items.append({'name': getattr(obj, 'name', _('Unnamed')), 'obj': obj}) related_items.sort(key=lambda o: o['name']) related_items = [o['obj'] for o in related_items] geojson = create_geojson(related_items) return dict(project=project, geojson=geojson)
def project_view(request, id=''): project = get_object_or_404(Project, pk=id) proj_objects, items = {}, [] proj_objects['User'] = {'app_name': 'authentication', 'objects_list': [{ 'name': project.creator.name, 'link': project.creator.view_url, 'id': project.creator.id, 'has_geojson': bool(getattr(project.creator, 'geometry', '')) }]} for c in project.contributors.all(): if c != project.creator: proj_objects['User']['objects_list'].append({ 'name': c.name, 'link': c.view_url, 'id': c.id, 'has_geojson': bool(getattr(c, 'geometry', '')) }) for p in project.related_objects: obj = p.content_object if obj: if not proj_objects.get(obj.__class__.__name__, None): proj_objects[obj.__class__.__name__] = { 'app_name': obj.__module__.split('.')[0], 'objects_list': []} proj_objects[obj.__class__.__name__]['objects_list'].append({ 'name': obj.name.strip(), 'link': obj.view_url, 'id': obj.id, 'has_geojson': bool(getattr(obj, 'geometry', '')) }) if isinstance(obj, Organization): branchs = [b for b in obj.organizationbranch_set.all()] if branchs: items += branchs elif not obj.is_empty(): items.append(obj) geojson = create_geojson(items) # ugly sort for key in proj_objects.iterkeys(): proj_objects[key]['objects_list'].sort(key=lambda o: o['name']) return dict(project=project, geojson=geojson, proj_objects=proj_objects, user_can_discuss=project.user_can_discuss(request.user))
def project_map(request, id=''): project = get_object_or_404(Project, pk=id) related_items = [] for obj in project.related_items: if obj and not obj.is_empty(): related_items.append({ 'name': getattr(obj, 'name', _('Unnamed')), 'obj': obj }) related_items.sort(key=lambda o: o['name']) related_items = [o['obj'] for o in related_items] geojson = create_geojson(related_items) return dict(project=project, geojson=geojson)
def edit_organization(request, id="", *arg, **kwargs): organization = get_object_or_None(Organization, pk=id) or Organization() geojson = create_geojson([organization], convert=False) if geojson and geojson.get("features"): geojson["features"][0]["properties"]["userCanEdit"] = True geojson = json.dumps(geojson) def on_get(request, form): form = FormOrganizationGeoRef(instance=organization) form.helper.form_action = reverse("edit_organization", kwargs={"id": organization.id}) return form def on_after_save(request, obj): return {"redirect": reverse("view_organization", kwargs={"id": obj.id})} return {"on_get": on_get, "on_after_save": on_after_save, "geojson": geojson, "organization": organization}
def get_geojson(request): bounds = request.GET.get('bounds', None) zoom = int(request.GET.get('zoom', 13)) x1, y2, x2, y1 = [float(i) for i in bounds.split(',')] polygon = Polygon(((x1, y1), (x1, y2), (x2, y2), (x2, y1), (x1, y1))) intersects_polygon = (Q(points__intersects=polygon) | Q(lines__intersects=polygon) | Q(polys__intersects=polygon)) d = _fetch_geo_objects(intersects_polygon, zoom) l = [] for objs in d.values(): l.extend(objs) geojson = create_geojson(l) return HttpResponse(json.dumps(geojson), mimetype="application/x-javascript")
def edit_community(request, id='', *args, **kwargs): community = get_object_or_404(Community, pk=id) if id else Community() geojson = create_geojson([community], convert=False) if geojson and geojson.get('features'): geojson['features'][0]['properties']['userCanEdit'] = True geojson = json.dumps(geojson) def on_get(request, form_community): return CommunityForm(instance=community) def on_after_save(request, obj): url = reverse('view_community', args=(obj.id,)) return {'redirect': url} return {'on_get': on_get, 'on_after_save': on_after_save, 'community': community, 'geojson': geojson}
def komoo_search(request): """ search view for the index page. It uses the parameters from the 'queries' dict to perform specific queries on the database """ logger.debug('Komoo_search: {}'.format(request.POST)) term = request.POST.get('term', '') result = {} for key, model in queries.iteritems(): result[key] = [] for o in _query_model(model.get('model'), term, model.get('query_fields')): dados = { 'id': o.id, 'name': getattr(o, model.get('repr')), 'link': model.get('link')(o), 'model': key, 'has_geojson': _has_geojson(o), 'geojson': create_geojson([o]) } if o.__class__.__name__ == 'Organization' and o.branch_count > 0: dados['branches'] = [] for b in o.organizationbranch_set.all(): dados['branches'].append({ 'id': b.id, 'name': getattr(b, model.get('repr')), 'model': key, 'has_geojson': _has_geojson(b), }) result[key].append(dados) # Google search google_results = requests.get( 'https://maps.googleapis.com/maps/api/place/autocomplete/json', params={ 'input': term, 'sensor': 'false', 'types': 'geocode', 'key': 'AIzaSyDgx2Gr0QeIASfirdAUoA0jjOs80fGtBYM', # TODO: move to settings }) result['google'] = google_results.content return {'result': result}
def get_geojson(request): """View used by the map javascript to fetch geojson data for each map tile. This view receives some parameters via GET request and returns a geojson reponse. Params: bounds: string of the form "lat_lo,lng_lo,lat_hi,lng_hi", where "lo" corresponds to the southwest corner of the bounding box, while "hi" corresponds to the northeast corner of that box. zoom: the map zoom level. models: a list of model to filter, separated by comma, of the form "app_name.ModelNamel". project - the id of the the project with which the filtered objects should have ralations. (Optional) """ bounds = request.GET.get('bounds', None) zoom = int(request.GET.get('zoom', 13)) models = request.GET.get('models', '') project = request.GET.get('project', None) if not bounds and not project: return HttpResponseBadRequest(to_json({'error': 'Invalid query'}), mimetype="application/x-javascript") if bounds: x1, y2, x2, y1 = [float(i) for i in bounds.split(',')] polygon = Polygon(((x1, y1), (x1, y2), (x2, y2), (x2, y1), (x1, y1))) intersects_polygon = (Q(points__intersects=polygon) | Q(lines__intersects=polygon) | Q(polys__intersects=polygon)) else: intersects_polygon = Q() models = [cache.get_model(*m.split('.')) for m in models.split(',') if m] d = _fetch_geo_objects(intersects_polygon, zoom, models, project) l = [] for objs in d.values(): l.extend(objs) geojson = create_geojson(l) return HttpResponse(to_json(geojson), mimetype="application/x-javascript")
def edit_need(request, id=""): need = get_object_or_404(Need, pk=id) geojson = create_geojson([need], convert=False) if geojson and geojson.get('features'): geojson['features'][0]['properties']['userCanEdit'] = True geojson = json.dumps(geojson) def on_get(request, form): form = NeedFormGeoRef(instance=need) form.helper.form_action = reverse('new_need') return form def on_after_save(request, need): redirect_url = reverse('view_need', kwargs={'id': need.pk}) return {'redirect': redirect_url} return {'on_get': on_get, 'on_after_save': on_after_save, 'geojson': geojson, 'need': need}
def edit_resource(request, id="", *arg, **kwargs): resource = get_object_or_None(Resource, pk=id) geojson = create_geojson([resource], convert=False) if geojson and geojson.get("features"): geojson["features"][0]["properties"]["userCanEdit"] = True geojson = to_json(geojson) def on_get(request, form): form = FormResourceGeoRef(instance=resource) form.helper.form_action = reverse("edit_resource", kwargs={"id": id}) return form def on_after_save(request, obj): versionate(request.user, obj) return {"redirect": obj.view_url} return {"on_get": on_get, "on_after_save": on_after_save, "geojson": geojson, "resource": resource}
def edit_need(request, id=""): need = get_object_or_404(Need, pk=id) geojson = create_geojson([need], convert=False) if geojson and geojson.get('features'): geojson['features'][0]['properties']['userCanEdit'] = True geojson = json.dumps(geojson) def on_get(request, form): form = NeedFormGeoRef(instance=need) form.helper.form_action = reverse('edit_need', kwargs={'id': id}) return form def on_after_save(request, need): redirect_url = reverse('view_need', kwargs={'id': need.pk}) return {'redirect': redirect_url} return {'on_get': on_get, 'on_after_save': on_after_save, 'geojson': geojson, 'need': need}
def edit_resource(request, id='', *arg, **kwargs): resource = get_object_or_None(Resource, pk=id) geojson = create_geojson([resource], convert=False) if geojson and geojson.get('features'): geojson['features'][0]['properties']['userCanEdit'] = True geojson = json.dumps(geojson) def on_get(request, form): form = FormResourceGeoRef(instance=resource) form.helper.form_action = reverse('edit_resource', kwargs={'id': id}) return form def on_after_save(request, obj): return {'redirect': obj.view_url} return {'on_get': on_get, 'on_after_save': on_after_save, 'geojson': geojson, 'resource': resource}
def edit_organization(request, id='', *arg, **kwargs): organization = get_object_or_None(Organization, pk=id) or Organization() geojson = create_geojson([organization], convert=False) if geojson and geojson.get('features'): geojson['features'][0]['properties']['userCanEdit'] = True geojson = json.dumps(geojson) def on_get(request, form): form = FormOrganization(instance=organization) form.helper.form_action = reverse('edit_organization', kwargs={'id': organization.id}) return form def on_after_save(request, obj): return {'redirect': reverse('view_organization', kwargs={'id': obj.id})} return {'on_get': on_get, 'on_after_save': on_after_save, 'geojson': geojson, 'organization': organization}
def edit_community(request, id='', *args, **kwargs): community = get_object_or_404(Community, pk=id) if id else Community() geojson = create_geojson([community], convert=False) if geojson and geojson.get('features'): geojson['features'][0]['properties']['userCanEdit'] = True geojson = to_json(geojson) def on_get(request, form_community): return CommunityForm(instance=community) def on_after_save(request, obj): versionate(request.user, obj) url = reverse('view_community', args=(obj.id, )) return {'redirect': url} return { 'on_get': on_get, 'on_after_save': on_after_save, 'community': community, 'geojson': geojson }
def profile_update(request): signatures = [] for sig in Signature.objects.filter(user=request.user): try: ct = ContentType.objects.get_for_id(sig.content_type_id) obj = ct.get_object_for_this_type(pk=sig.object_id) signatures.append({ 'signature_id': sig.id, 'obj_name': getattr(obj, 'name', '') or getattr(obj, 'title', ''), 'obj_id': obj.id, 'model_name': ct.name, 'app_name': ct.app_label, 'permalink': obj.view_url, 'has_geojson': not 'EMPTY' in getattr(obj, 'geometry', 'EMPTY'), }) except: # signature for an object that cannot be found (probably deleted) sig.delete() digest_obj = DigestSignature.objects.filter(user=request.user) digest = digest_obj[0].digest_type if digest_obj.count() \ else 'N' form_profile = FormProfile(instance=request.user) geojson = create_geojson([request.user], convert=False) geojson['features'][0]['properties']['image'] = '/static/img/me.png' geojson = json.dumps(geojson) return dict(signatures=signatures, form_profile=form_profile, digest=digest, geojson=geojson)
def geojson(request, app_label, model_name, obj_id): model = get_model(app_label, model_name) obj = get_object_or_404(model, id=obj_id) if model else None geojson = getattr(obj, 'geojson', create_geojson([obj])) return HttpResponse(geojson, mimetype="application/x-javascript")
def on_map(request, id): community = get_object_or_404(Community, pk=id) geojson = create_geojson([community]) return dict(community=community, geojson=geojson)
def related(request, app_label, model_name, obj_id): model = get_model(app_label, model_name) obj = get_object_or_404(model, id=obj_id) if model else None return HttpResponse(create_geojson(getattr(obj, 'related_items', [])), mimetype="application/x-javascript")
def related(request, app_label, model_name, obj_id): model = get_model(app_label, model_name) obj = get_object_or_404(model, id=obj_id) if model else None return HttpResponse(create_geojson(getattr(obj, "related_items", [])), mimetype="application/x-javascript")
def related_items(request, id=""): organization = get_object_or_None(Organization, pk=id) or Organization() geojson = create_geojson(organization.related_items) return {"organization": organization, "geojson": geojson}
def related_items(request, id=''): organization = get_object_or_None(Organization, pk=id) or Organization() geojson = create_geojson(organization.related_items + [organization]) return {'organization': organization, 'geojson': geojson}
def show_on_map(request, geojson=''): resource = get_object_or_404(Resource, pk=request.GET.get('id', '')) geojson = create_geojson([resource]) return dict(geojson=geojson)
def geojson(obj=None): """Returns a geojson with obj data""" if obj.geometry.empty: return '{}' return create_geojson([obj]).replace("'", "\\'").replace('"', "'")
def related_items(request, id=''): organization = get_object_or_None(Organization, pk=id) or Organization() geojson = create_geojson(organization.related_items) return {'organization': organization, 'geojson': geojson}
def show_on_map(request, geojson=""): resource = get_object_or_404(Resource, pk=request.GET.get("id", "")) geojson = create_geojson([resource]) return dict(geojson=geojson)
def view(request, id=None): need = get_object_or_404(Need, pk=id) geojson = create_geojson([need]) return dict(need=need, geojson=geojson)
def geojson(self): items = [] for obj in self.related_items: if obj and not obj.is_empty(): items.append(obj) return create_geojson(items)
def geojson(self): geojson = create_geojson([self], convert=False) if geojson and geojson.get('features'): geojson['features'][0]['properties']['userCanEdit'] = True geojson['features'][0]['properties']['alwaysVisible'] = True return json.dumps(geojson)