Exemplo n.º 1
0
def get_iucn_status(taxon_id=None, species_name=None):
    """
    Fetch iucn status of the species, and update the iucn record.

    :param taxon_id: taxon id of the species
    :param species_name: name of the species
    """
    api_iucn_key = get_key('IUCN_API_KEY')

    if not api_iucn_key:
        return None

    api_url = settings.IUCN_API_URL

    if taxon_id:
        api_url += '/id/' + taxon_id
    elif species_name:
        api_url += '/species/' + species_name
    else:
        return None

    # Add token
    api_url += '?token=' + api_iucn_key

    try:
        response = requests.get(api_url)
        json_result = response.json()
        if len(json_result['result']) > 0:
            iucn_status, created = IUCNStatus.objects.get_or_create(
                category=json_result['result'][0]['category'])
            return iucn_status
        return None
    except (HTTPError, KeyError) as e:
        print(e)
        return None
Exemplo n.º 2
0
    def get_context_data(self, **kwargs):

        context = super(BioRecordsUpdateView, self).get_context_data(**kwargs)
        context['geometry_type'] = \
            self.object.site.location_type.allowed_geometry
        if context['geometry_type'] == 'POLYGON':
            context['geometry'] = \
                self.object.site.geometry_polygon.geojson
        elif context['geometry_type'] == 'LINE':
            context['geometry'] = \
                self.object.site.geometry_line.geojson
        else:
            context['geometry'] = \
                self.object.site.geometry_point.geojson

        context['bing_map_key'] = get_key('BING_MAP_KEY')

        context['all_references'] = ReferenceSerializer(Entry.objects.all(),
                                                        many=True).data

        reference_links = ReferenceLink.objects.filter(
            collection_record=self.object)
        context['references_link'] = []
        for reference in reference_links:
            context['references_link'].append(reference.reference.id)

        documents = self.object.documents.all()
        if documents:
            context['documents_selected'] = DocumentSerializer(documents,
                                                               many=True).data

        return context
Exemplo n.º 3
0
    def get_context_data(self, **kwargs):

        context = super(BioRecordsUpdateView, self).get_context_data(**kwargs)
        context['geometry_type'] = \
            self.object.site.location_type.allowed_geometry
        if context['geometry_type'] == 'POLYGON':
            context['geometry'] = \
                self.object.site.geometry_polygon.geojson
        elif context['geometry_type'] == 'LINE':
            context['geometry'] = \
                self.object.site.geometry_line.geojson
        else:
            context['geometry'] = \
                self.object.site.geometry_point.geojson

        context['bing_map_key'] = get_key('BING_MAP_KEY')

        context['all_references'] = ReferenceSerializer(Entry.objects.all(),
                                                        many=True).data
        context['id'] = self.object.id
        context['location_site_selected'] = self.object.site
        if self.object.source_reference:
            context['reference_category'] = (
                self.object.source_reference.reference_type)
            context['source_reference'] = self.object.source_reference.source

        return context
Exemplo n.º 4
0
def fetch_river_name(latitude, longitude):
    """
    Fetch river name from GeoContext
    :param latitude: LocationSite latitude
    :param longitude: LocationSite longitude
    """
    name = ''
    base_geocontext_url = get_key('GEOCONTEXT_URL')
    api_url = '/api/v1/geocontext/river-name/'
    y = latitude
    x = longitude
    geocontext_url = '{base}{api_url}{x}/{y}/'.format(
        base=base_geocontext_url,
        api_url=api_url,
        x=x,
        y=y
    )

    try:
        response = requests.get(geocontext_url)
        if response.status_code == 200:
            name = response.content
            name = name.decode('utf-8').strip('\"')
    except HTTPError:
        pass

    return name
    def get(self, request):
        lat = request.GET.get('lat', None)
        lon = request.GET.get('lon', None)
        geomorphological_group = {}
        geomorphological_zone = ''

        url = (
            '{base_url}/api/v1/geocontext/value/group/'
            '{lon}/{lat}/geomorphological_group/'
        ).format(
            base_url=get_key('GEOCONTEXT_URL'),
            lon=lon,
            lat=lat
        )

        try:
            response = requests.get(url)
            if response.status_code == 200:
                geomorphological_group = json.loads(response.content)
                geomorphological_zone = (
                    geomorphological_group['service_registry_values'][1][
                        'value']
                )
        except (HTTPError, ValueError, KeyError):
            pass

        return Response({
            'geomorphological_group': geomorphological_group,
            'geomorphological_zone': geomorphological_zone,
        })
Exemplo n.º 6
0
def application_name(request):
    """
    Return application name
    """
    name = get_key('APPLICATION_NAME')
    if not name:
        name = 'Django BIMS'
    return {'APPLICATION_NAME': name}
Exemplo n.º 7
0
def site_ready(request):
    """
    Return if site is ready
    """
    try:
        is_site_ready = ast.literal_eval(get_key('SITE_READY'))
    except (ValueError, SyntaxError):
        is_site_ready = False
    return {'site_ready': is_site_ready}
Exemplo n.º 8
0
    def get_context_data(self, **kwargs):
        context = super(CollectionFormView, self).get_context_data(**kwargs)
        if not self.location_site:
            return context
        context['geoserver_public_location'] = get_key(
            'GEOSERVER_PUBLIC_LOCATION')
        context['location_site_name'] = self.location_site.name
        context['location_site_code'] = self.location_site.site_code
        context['location_site_lat'] = self.location_site.get_centroid().y
        context['location_site_long'] = self.location_site.get_centroid().x
        context['site_id'] = self.location_site.id
        context['taxa'] = self.taxa_from_river_catchment()
        context['taxon_rank'] = list(rank.name
                                     for rank in TaxonomicRank.hierarchy())
        context['reference_category'] = list(
            BiologicalCollectionRecord.objects.
            filter(reference_category__isnull=False).exclude(
                reference_category='').distinct('reference_category').values(
                    name=F('reference_category')))
        context['taxon_group_name'] = self.taxon_group_name
        taxon_group = TaxonGroup.objects.filter(name=self.taxon_group_name)
        context['broad_biotope_list'] = list(
            Biotope.objects.filter(
                taxon_group__in=taxon_group,
                biotope_type=BIOTOPE_TYPE_BROAD).values(
                    'id', 'name', 'description',
                    'display_order').order_by('display_order'))
        context['specific_biotope_list'] = list(
            Biotope.objects.filter(
                taxon_group__in=taxon_group,
                biotope_type=BIOTOPE_TYPE_SPECIFIC).values(
                    'id', 'name', 'description',
                    'display_order').order_by('display_order'))

        context['substratum_list'] = list(
            Biotope.objects.filter(
                taxon_group__in=taxon_group,
                biotope_type=BIOTOPE_TYPE_SUBSTRATUM).values(
                    'id', 'name', 'description',
                    'display_order').order_by('display_order'))

        sampling_method_lower_list = []
        context['sampling_method_list'] = []
        sampling_method_list = list(
            SamplingMethod.objects.filter(taxon_group__in=taxon_group).values(
                'id', 'sampling_method').order_by('order'))
        for sampling_method in sampling_method_list:
            sampling_method_name = (sampling_method['sampling_method'].replace(
                '-', ' ')).strip()
            if sampling_method_name.lower() not in sampling_method_lower_list:
                sampling_method_lower_list.append(sampling_method_name.lower())
                context['sampling_method_list'].append(sampling_method)

        return context
Exemplo n.º 9
0
    def update_location_context_document(self):
        """Update location context document."""
        LOGGER.debug('update_location_context_document')
        geocontext_url = get_key('GEOCONTEXT_URL')
        geocontext_collection_key = get_key('GEOCONTEXT_COLLECTION_KEY')
        if not geocontext_url:
            message = (
                'Can not update location context document because geocontext '
                'url is None. Please set it.')
            return False, message
        if not geocontext_collection_key:
            message = (
                'Can not update location context document because geocontext '
                'collection key is None. Please set it.')
            return False, message
        if not self.get_centroid():
            message = (
                'Can not update location context document because centroid is '
                'None. Please set it.')
            return False, message
        longitude = self.get_centroid().x
        latitude = self.get_centroid().y

        # build url
        url = self.geocontext_url_format.format(
            geocontext_url=geocontext_url,
            longitude=longitude,
            latitude=latitude,
            geocontext_collection_key=geocontext_collection_key,
        )

        r = requests.get(url)
        if r.status_code != 200:
            message = (
                'Request to url %s got %s [%s], can not update location '
                'context document.' % (url, r.status_code, r.reason))
            return False, message

        self.location_context_document = json.dumps(r.json())
        return True, 'Successfully update location context document.'
Exemplo n.º 10
0
 def get_context_data(self, **kwargs):
     context = super(LocationSiteFormView, self).get_context_data(**kwargs)
     context['geoserver_public_location'] = get_key(
         'GEOSERVER_PUBLIC_LOCATION')
     context['geomorphological_zone_category'] = [
         (g.name, g.value) for g in GEOMORPHOLOGICAL_ZONE_CATEGORY_ORDER
     ]
     if self.request.user.get_full_name():
         context['fullname'] = self.request.user.get_full_name()
     else:
         context['fullname'] = self.request.user.username
     context['user_id'] = self.request.user.id
     context.update(self.additional_context_data())
     return context
Exemplo n.º 11
0
    def get_context_data(self, **kwargs):
        """Get the context data which is passed to a template.

        :param kwargs: Any arguments to pass to the superclass.
        :type kwargs: dict

        :returns: Context data which will be passed to the template.
        :rtype: dict
        """
        context = super(MapPageView, self).get_context_data(**kwargs)
        context['bing_map_key'] = get_key('BING_MAP_KEY')
        context['map_tiler_key'] = get_key('MAP_TILER_KEY')
        context['geocontext_url'] = get_key('GEOCONTEXT_URL')
        context['geocontext_collection_key'] = get_key(
            'GEOCONTEXT_COLLECTION_KEY')
        context['center_point_map'] = get_key('CENTER_POINT_MAP')

        categories = BiologicalCollectionRecord.CATEGORY_CHOICES
        context['collection_category'] = [list(x) for x in categories]

        bio_childrens = BiologicalCollectionRecord.get_children_model()
        context['biological_modules'] = {
            bio._meta.app_label: str(bio._meta.label)
            for bio in bio_childrens
        }

        # get date filter
        context['date_filter'] = {'min': '1900', 'max': '2008'}
        date_min = BiologicalCollectionRecord.objects.all().aggregate(
            min=Min('collection_date'))['min']
        date_max = BiologicalCollectionRecord.objects.all().aggregate(
            max=Max('collection_date'))['max']
        if date_min:
            context['date_filter']['min'] = date_min.year
        if date_max:
            context['date_filter']['max'] = date_max.year
        return context
Exemplo n.º 12
0
    def get(self, request):
        lat = request.GET.get('lat', None)
        lon = request.GET.get('lon', None)
        site_id = request.GET.get('site_id', None)
        location_site = None
        if site_id:
            try:
                location_site = LocationSite.objects.get(id=site_id)
            except LocationSite.DoesNotExist:
                pass

        catchment = ''
        secondary_catchment_area = ''

        river_name = fetch_river_name(lat, lon)

        catchment_url = ('{base_url}/api/v1/geocontext/value/group/'
                         '{lon}/{lat}/river_catchment_areas_group/').format(
                             base_url=get_key('GEOCONTEXT_URL'),
                             lon=lon,
                             lat=lat)

        try:
            response = requests.get(catchment_url)
            if response.status_code == 200:
                catchment = json.loads(response.content)
                secondary_catchment_area = (
                    catchment['service_registry_values'][1]['value'])
        except (HTTPError, ValueError, KeyError):
            pass

        return Response({
            'river':
            river_name,
            'catchment':
            catchment,
            'site_code':
            generate_site_code(river_name=river_name,
                               catchment=secondary_catchment_area,
                               location_site=location_site)
        })
Exemplo n.º 13
0
    def get_context_data(self, **kwargs):
        context = super(FishFormView, self).get_context_data(**kwargs)
        if not self.location_site:
            return context
        context['geoserver_public_location'] = get_key(
            'GEOSERVER_PUBLIC_LOCATION')
        context['location_site_name'] = self.location_site.name
        context['location_site_code'] = self.location_site.site_code
        context['location_site_lat'] = self.location_site.get_centroid().y
        context['location_site_long'] = self.location_site.get_centroid().x
        context['site_id'] = self.location_site.id
        context['taxa'] = self.taxa_from_river_catchment()
        context['reference_category'] = list(
            BiologicalCollectionRecord.objects.
            filter(reference_category__isnull=False).exclude(
                reference_category='').distinct('reference_category').values(
                    name=F('reference_category')))
        context['biotope_list'] = list(
            Biotope.objects.filter(
                taxon_group__name__icontains='fish',
                taxon_group__category='SPECIES_MODULE').values(
                    'name', 'description',
                    'display_order').order_by('display_order'))

        sampling_method_lower_list = []
        context['sampling_method_list'] = []
        sampling_method_list = list(SamplingMethod.objects.all().values(
            'id', 'sampling_method').order_by(
                F('normalisation_factor').asc(nulls_first=True)))
        for sampling_method in sampling_method_list:
            sampling_method_name = (sampling_method['sampling_method'].replace(
                '-', ' ')).strip()
            if sampling_method_name.lower() not in sampling_method_lower_list:
                sampling_method_lower_list.append(sampling_method_name.lower())
                context['sampling_method_list'].append(sampling_method)

        return context
Exemplo n.º 14
0
    def get_geocontext_group_data(self, group_key):
        LOGGER.debug('get_location_group_data for ' + group_key)
        geocontext_url = get_key('GEOCONTEXT_URL')
        if not geocontext_url:
            message = (
                'Can not update location context document because geocontext '
                'url is None. Please set it.')
            return False, message
        if not self.get_centroid():
            message = (
                'Can not update location context document because centroid is '
                'None. Please set it.')
            return False, message
        longitude = self.get_centroid().x
        latitude = self.get_centroid().y

        geocontext_group_url_format = (
            '{geocontext_url}/api/v1/geocontext/value/group/'
            '{longitude}/{latitude}/{geocontext_group_key}')
        # build url
        url = geocontext_group_url_format.format(
            geocontext_url=geocontext_url,
            longitude=longitude,
            latitude=latitude,
            geocontext_group_key=group_key,
        )
        LOGGER.info('Request url : {}'.format(url))

        r = requests.get(url)
        if r.status_code != 200:
            message = (
                'Request to url %s got %s [%s], can not update location '
                'context document.' % (url, r.status_code, r.reason))
            LOGGER.info(message)
            return None

        return json.dumps(r.json())
Exemplo n.º 15
0
def google_analytic_key(request):
    """
    Return google analytic key
    """
    return {'GOOGLE_ANALYTIC_KEY': get_key('GOOGLE_ANALYTIC_KEY')}
Exemplo n.º 16
0
    def get_context_data(self, **kwargs):
        """Get the context data which is passed to a template.

        :param kwargs: Any arguments to pass to the superclass.
        :type kwargs: dict

        :returns: Context data which will be passed to the template.
        :rtype: dict
        """
        context = super(MapPageView, self).get_context_data(**kwargs)
        context['bing_map_key'] = get_key('BING_MAP_KEY')
        context['map_tiler_key'] = get_key('MAP_TILER_KEY')
        context['map_surfer_key'] = get_key('MAP_SURFER_KEY')
        context['geocontext_url'] = get_key('GEOCONTEXT_URL')
        context['geocontext_collection_key'] = get_key(
            'GEOCONTEXT_COLLECTION_KEY')
        context['center_point_map'] = get_key('CENTER_POINT_MAP')
        context['can_validate'] = user_has_permission_to_validate(
            self.request.user)
        context['geoserver_public_location'] = get_key(
            'GEOSERVER_PUBLIC_LOCATION')

        categories = BiologicalCollectionRecord.CATEGORY_CHOICES
        context['collection_category'] = [list(x) for x in categories]
        # add base module
        context['biological_modules'] = {'base': 'base'}

        # Additional filters
        context['use_ecological_condition'] = bool(
            get_key('ECOLOGICAL_CONDITION_FILTER'))
        context['use_conservation_status'] = bool(
            get_key('CONSERVATION_STATUS_FILTER'))

        # Search panel titles
        date_title = get_key('DATE_TITLE')
        if not date_title:
            date_title = 'TEMPORAL'
        context['date_title'] = date_title

        spatial_scale = get_key('SPATIAL_SCALE_TITLE')
        if not spatial_scale:
            spatial_scale = 'SPATIAL'
        context['spatial_scale_title'] = spatial_scale

        # get date filter
        context['date_filter'] = {'min': '1900', 'max': '2008'}
        date_min = BiologicalCollectionRecord.objects.all().aggregate(
            min=Min('collection_date'))['min']
        date_max = BiologicalCollectionRecord.objects.all().aggregate(
            max=Max('collection_date'))['max']
        if date_min:
            context['date_filter']['min'] = date_min.year
        if date_max:
            context['date_filter']['max'] = date_max.year

        # Is it necessary to use collector filter, default true
        collector_filter = get_key(self.COLLECTOR_FILTER)
        if not collector_filter:
            context[self.COLLECTOR_FILTER] = True
        else:
            context[self.COLLECTOR_FILTER] = distutil.strtobool(
                collector_filter)

        if self.request.user:
            try:
                user_profile = BimsProfile.objects.get(user=self.request.user)
                context['hide_bims_info'] = user_profile.hide_bims_info
            except (BimsProfile.DoesNotExist, TypeError):
                pass

        # Get all the iucn conservation status
        if context['use_conservation_status']:
            iucn_statuses = IUCNStatus.objects.all().distinct('category')
            conservation_status_data = []
            conservation_status_desc = {
                'CR':
                'A taxon is Critically Endangered when the best '
                'available evidence indicates that it is considered '
                'to be facing an extremely high risk of extinction in '
                'the wild.',
                'EN':
                'A taxon is Endangered when it is considered to be '
                'facing a very high risk of extinction in the wild.',
                'VU':
                'A taxon is Vulnerable when the best available evidence '
                'indicates that it is considered to be facing a high '
                'risk of extinction in the wild.',
                'NT':
                'A taxon is Near Threatened when it has been evaluated '
                'against the criteria but does not qualify for '
                'Critically Endangered, Endangered or Vulnerable now, '
                'but is close to qualifying for or is likely to qualify '
                'for a threatened category in the near future.',
                'LC':
                'A taxon is Least Concern when it has been evaluated '
                'against the criteria and does not qualify for '
                'Critically Endangered, Endangered, Vulnerable or '
                'Near Threatened. Widespread and abundant taxa are '
                'included in this category.',
                'DD':
                'A taxon is Data Deficient when there is inadequate '
                'information to make a direct, or indirect, assessment '
                'of its risk of extinction based on its distribution '
                'and/or population status. A taxon in this category'
                ' may be well studied, and its biology well known, '
                'but appropriate data on abundance and/or distribution '
                'are lacking. Data Deficient is therefore not a '
                'category of threat. Listing of taxa in this category '
                'indicates that more information is required and '
                'acknowledges the possibility that future research '
                'will show that threatened classification is '
                'appropriate. '
                'It is important to make positive use of whatever '
                'data are '
                'available. In many cases great care should be '
                'exercised '
                'in choosing between DD and a threatened status. '
                'If the range of a taxon is suspected to be relatively '
                'circumscribed, and a considerable period of time has '
                'elapsed since the last record of the taxon, threatened '
                'status may well be justified.',
                'NE':
                'A taxon is Not Evaluated when it has not '
                'yet been evaluated against the criteria.'
            }
            categories = dict(IUCNStatus.CATEGORY_CHOICES)
            for iucn_status in iucn_statuses:
                status = str(iucn_status.category)
                desc = ''
                if status in conservation_status_desc:
                    desc = conservation_status_desc[status]
                conservation_status_data.append({
                    'status':
                    str(iucn_status.category),
                    'name':
                    categories[iucn_status.category].title(),
                    'desc':
                    desc
                })
            context['conservation_status_data'] = conservation_status_data

        try:
            context['flatpage'] = FlatPage.objects.get(title__icontains='info')
        except FlatPage.DoesNotExist:
            pass

        return context
Exemplo n.º 17
0
    def get_context_data(self, **kwargs):
        """Get the context data which is passed to a template.

        :param kwargs: Any arguments to pass to the superclass.
        :type kwargs: dict

        :returns: Context data which will be passed to the template.
        :rtype: dict
        """
        context = super(MapPageView, self).get_context_data(**kwargs)
        context['bing_map_key'] = get_key('BING_MAP_KEY')
        context['map_tiler_key'] = get_key('MAP_TILER_KEY')
        context['geocontext_url'] = get_key('GEOCONTEXT_URL')
        context['geocontext_collection_key'] = get_key(
            'GEOCONTEXT_COLLECTION_KEY')
        context['center_point_map'] = get_key('CENTER_POINT_MAP')
        context['can_validate'] = user_has_permission_to_validate(
                self.request.user)

        categories = BiologicalCollectionRecord.CATEGORY_CHOICES
        context['collection_category'] = [list(x) for x in categories]

        # Additional filters
        context['use_ecological_condition'] = bool(
                get_key('ECOLOGICAL_CONDITION_FILTER'))
        context['use_conservation_status'] = bool(
                get_key('CONSERVATION_STATUS_FILTER'))

        # Search panel titles
        date_title = get_key('DATE_TITLE')
        if not date_title:
            date_title = 'DATE'
        context['date_title'] = date_title

        spatial_scale = get_key('SPATIAL_SCALE_TITLE')
        if not spatial_scale:
            spatial_scale = 'ADMINISTRATIVE AREA'
        context['spatial_scale_title'] = spatial_scale

        # get date filter
        context['date_filter'] = {'min': '1900', 'max': '2008'}
        date_min = BiologicalCollectionRecord.objects.all(
        ).aggregate(min=Min('collection_date'))['min']
        date_max = BiologicalCollectionRecord.objects.all(
        ).aggregate(max=Max('collection_date'))['max']
        if date_min:
            context['date_filter']['min'] = date_min.year
        if date_max:
            context['date_filter']['max'] = date_max.year

        # Is it necessary to use collector filter, default true
        collector_filter = get_key(self.COLLECTOR_FILTER)
        if not collector_filter:
            context[self.COLLECTOR_FILTER] = True
        else:
            context[self.COLLECTOR_FILTER] = distutil.strtobool(
                    collector_filter)

        if self.request.user:
            try:
                user_profile = BimsProfile.objects.get(user=self.request.user)
                context['hide_bims_info'] = user_profile.hide_bims_info
            except (BimsProfile.DoesNotExist, TypeError):
                pass

        # Get all the iucn conservation status
        if context['use_conservation_status']:
            iucn_statuses = IUCNStatus.objects.all().distinct('category')
            conservation_status_data = []
            categories = dict(IUCNStatus.CATEGORY_CHOICES)
            for iucn_status in iucn_statuses:
                conservation_status_data.append({
                    'status': str(iucn_status.category),
                    'name': categories[iucn_status.category]
                })
            context['conservation_status_data'] = conservation_status_data

        try:
            context['flatpage'] = FlatPage.objects.get(title__icontains='info')
        except FlatPage.DoesNotExist:
            pass

        return context
Exemplo n.º 18
0
    def get_context_data(self, **kwargs):
        context = super(SassFormView, self).get_context_data(**kwargs)

        sass_created_id = self.request.GET.get('sass_created_id', None)
        if sass_created_id:
            try:
                sass_created = SiteVisit.objects.get(id=sass_created_id)
                context['alert'] = ('New SASS data has been added : '
                                    '<a href="/sass/view/{0}">{1}</a>'.format(
                                        sass_created_id,
                                        sass_created.site_visit_date))
            except SiteVisit.DoesNotExist:
                pass

        if self.site_visit:
            context['is_update'] = True
            context['site_visit_id'] = self.site_visit.id
            context['collector'] = self.site_visit.collector
            context['date'] = self.site_visit.site_visit_date
            context['time'] = self.site_visit.time
            context['site_identifier'] = (
                self.site_visit.location_site.location_site_identifier)
            context['site_id'] = self.site_visit.location_site.id
            owner = self.site_visit.owner
            if self.site_visit.comments_or_observations:
                context['comments'] = self.site_visit.comments_or_observations
            if self.site_visit.other_biota:
                context['other_biota'] = self.site_visit.other_biota

            # Get source reference
            site_visit_taxon = SiteVisitTaxon.objects.filter(
                site_visit=self.site_visit, source_reference__isnull=False)
            if site_visit_taxon.exists():
                source_reference = site_visit_taxon[0].source_reference
                context['source_reference'] = source_reference
        else:
            owner = self.request.user

        if owner:
            context['owner'] = owner
            bims_profile, created = BimsProfile.objects.get_or_create(
                user=owner)
            if self.site_visit:
                context['accredited'] = bims_profile.is_accredited(
                    collection_date=self.site_visit.site_visit_date)

        context['biotope_form_list'] = self.get_biotope_form_data()
        context['taxon_list'] = self.get_taxon_list()
        context['site_code'] = self.site_code
        context['location_site_lat'] = self.site_lat
        context['location_site_lon'] = self.site_lon
        context['geoserver_public_location'] = get_key(
            'GEOSERVER_PUBLIC_LOCATION')
        if self.site_visit:
            try:
                self.site_image = (SiteImage.objects.get(
                    site_visit=self.site_visit))
                context['site_image'] = self.site_image
            except SiteImage.DoesNotExist:
                pass
            context['sass_version'] = self.site_visit.sass_version

        return context
Exemplo n.º 19
0
    def get_context_data(self, **kwargs):
        """Get the context data which is passed to a template.

        :param kwargs: Any arguments to pass to the superclass.
        :type kwargs: dict

        :returns: Context data which will be passed to the template.
        :rtype: dict
        """
        context = super(MapPageView, self).get_context_data(**kwargs)
        context['bing_map_key'] = get_key('BING_MAP_KEY')
        context['map_tiler_key'] = get_key('MAP_TILER_KEY')
        context['geocontext_url'] = get_key('GEOCONTEXT_URL')
        context['geocontext_collection_key'] = get_key(
            'GEOCONTEXT_COLLECTION_KEY')
        context['center_point_map'] = get_key('CENTER_POINT_MAP')
        context['can_validate'] = user_has_permission_to_validate(
                self.request.user)

        categories = BiologicalCollectionRecord.CATEGORY_CHOICES
        context['collection_category'] = [list(x) for x in categories]

        bio_childrens = BiologicalCollectionRecord.get_children_model()

        # add additional module
        context['biological_modules'] = {
            bio._meta.app_label: str(bio._meta.label) for bio in bio_childrens
        }
        # add base module
        context['modules_exists'] = bool(context['biological_modules'])
        context['biological_modules']['base'] = 'base'

        # Additional filters
        context['use_ecological_condition'] = bool(
                get_key('ECOLOGICAL_CONDITION_FILTER'))
        context['use_conservation_status'] = bool(
                get_key('CONSERVATION_STATUS_FILTER'))

        # Search panel titles
        date_title = get_key('DATE_TITLE')
        if not date_title:
            date_title = 'DATE'
        context['date_title'] = date_title

        spatial_scale = get_key('SPATIAL_SCALE_TITLE')
        if not spatial_scale:
            spatial_scale = 'ADMINISTRATIVE AREA'
        context['spatial_scale_title'] = spatial_scale

        # get date filter
        context['date_filter'] = {'min': '1900', 'max': '2008'}
        date_min = BiologicalCollectionRecord.objects.all(
        ).aggregate(min=Min('collection_date'))['min']
        date_max = BiologicalCollectionRecord.objects.all(
        ).aggregate(max=Max('collection_date'))['max']
        if date_min:
            context['date_filter']['min'] = date_min.year
        if date_max:
            context['date_filter']['max'] = date_max.year

        if self.request.user:
            try:
                user_profile = BimsProfile.objects.get(user=self.request.user)
                context['hide_bims_info'] = user_profile.hide_bims_info
            except (BimsProfile.DoesNotExist, TypeError):
                pass

        try:
            context['flatpage'] = FlatPage.objects.get(title__icontains='info')
        except FlatPage.DoesNotExist:
            pass

        return context
Exemplo n.º 20
0
from django.test import TestCase
from django.contrib.gis.geos import LineString, Point
from django.core.exceptions import ValidationError
from django.db.models import signals
from bims.tests.model_factories import (
    LocationTypeF,
    LocationSiteF,
    TaxonF,
    IUCNStatusF,
    SurveyF,
)
from bims.models.iucn_status import iucn_status_pre_save_handler
from bims.utils.get_key import get_key
from bims.models.location_site import LocationSite

geocontext_url = get_key('GEOCONTEXT_URL')
geocontext_collection_key = get_key('GEOCONTEXT_COLLECTION_KEY')

skip_geocontext = (not geocontext_url or not geocontext_collection_key)

first_url = LocationSite.geocontext_url_format.format(
    geocontext_url=geocontext_url,
    longitude='27.0',
    latitude='-31.0',
    geocontext_collection_key=geocontext_collection_key,
)

second_url = LocationSite.geocontext_url_format.format(
    geocontext_url=geocontext_url,
    longitude='26.0',
    latitude='-30.0',
Exemplo n.º 21
0
PIPELINE['JS_COMPRESSOR'] = 'pipeline.compressors.yui.YUICompressor'
PIPELINE['CSS_COMPRESSOR'] = 'pipeline.compressors.yui.YUICompressor'
PIPELINE_YUI_JS_ARGUMENTS = '--nomunge'
PIPELINE_DISABLE_WRAPPER = True

# Comment if you are not running behind proxy
USE_X_FORWARDED_HOST = True

# Set debug to false for production
DEBUG = TEMPLATE_DEBUG = False

SERVER_EMAIL = '*****@*****.**'
EMAIL_HOST = 'kartoza.com'
DEFAULT_FROM_EMAIL = '*****@*****.**'

sentry_key = get_key('SENTRY_KEY')

# Logging
if 'raven.contrib.django.raven_compat' in INSTALLED_APPS and sentry_key:
    # noinspection PyUnresolvedReferences
    import raven  # noqa

    # The version file is made by the tag_and_deploy script
    version_file = join(dirname(dirname(dirname(__file__))), '.version')
    if exists(version_file):
        with open(version_file, 'r') as version:
            release = version.read()
    else:
        release = 'unknown'

    RAVEN_CONFIG = {