Exemplo n.º 1
0
def _serialize_unknown(obj):
    # Handle NewsItems and various other types that default json serializer
    # doesn't know how to do.
    if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)):
        return serialize_date_or_time(obj)
    elif is_instance_of_model(obj, models.Lookup):
        return obj.name
    elif is_instance_of_model(obj, models.NewsItem):
        return _item_geojson_dict(obj)
    return None
Exemplo n.º 2
0
def _serialize_unknown(obj):
    # Handle NewsItems and various other types that default json serializer
    # doesn't know how to do.
    if isinstance(obj, (datetime.datetime, datetime.date, datetime.time)):
        return serialize_date_or_time(obj)
    elif is_instance_of_model(obj, models.Lookup):
        return obj.name
    elif is_instance_of_model(obj, models.NewsItem):
        return _item_geojson_dict(obj)
    return None
Exemplo n.º 3
0
def json_lookup_values_for_attribute(schema_slug, sf_name):
    """Given a schema slug and attribute name, returns
    all the current Lookup values of the relevant attribute,
    as a JSON-formatted list.

    Assumes the relevant schemafield has is_lookup=True.

    Example:

    .. code-block:: html+django

     <script>
      var lookups = {% json_lookup_values_for_attribute 'police-reports' 'violations' %};
     </script>

    Example output:

    .. code-block:: html+django

     <script>
      var lookups = ['burglary', 'speeding', 'vandalism'];
     </script>
    """
    if is_instance_of_model(schema_slug, Schema):
        schema_slug = schema_slug.slug
    values = Lookup.objects.filter(schema_field__schema__slug=schema_slug, schema_field__name=sf_name).values_list(
        "name"
    )
    values = [d[0] for d in values]
    return json.dumps(sorted(values))
Exemplo n.º 4
0
def json_lookup_values_for_attribute(schema_slug, sf_name):
    """Given a schema slug and attribute name, returns
    all the current Lookup values of the relevant attribute,
    as a JSON-formatted list.

    Assumes the relevant schemafield has is_lookup=True.

    Example:

    .. code-block:: html+django

     <script>
      var lookups = {% json_lookup_values_for_attribute 'police-reports' 'violations' %};
     </script>

    Example output:

    .. code-block:: html+django

     <script>
      var lookups = ['burglary', 'speeding', 'vandalism'];
     </script>
    """
    if is_instance_of_model(schema_slug, Schema):
        schema_slug = schema_slug.slug
    values = Lookup.objects.filter(
        schema_field__schema__slug=schema_slug,
        schema_field__name=sf_name).values_list('name')
    values = [d[0] for d in values]
    return json.dumps(sorted(values))
Exemplo n.º 5
0
 def test_is_instance_of_model(self):
     from ebpub.utils.models import is_instance_of_model
     from django.contrib.gis.db import models
     class Foo(models.Model):
         class Meta:
             app_label = 'openblockapi'
     f = Foo()
     self.assertEqual(True, is_instance_of_model(f, Foo))
     self.assertRaises(TypeError, is_instance_of_model, f, Foo())
Exemplo n.º 6
0
    def test_is_instance_of_model(self):
        from ebpub.utils.models import is_instance_of_model
        from django.contrib.gis.db import models

        class Foo(models.Model):
            class Meta:
                app_label = "openblockapi"

        f = Foo()
        self.assertEqual(True, is_instance_of_model(f, Foo))
        self.assertRaises(TypeError, is_instance_of_model, f, Foo())
Exemplo n.º 7
0
    def render(self, context):
        """Puts some information about overlapping locations into context[varname].
        """
        newsitem_context = self.newsitem_context_var.resolve(context)
        if isinstance(newsitem_context, dict):
            newsitem = newsitem_context.get('_item', None)
        else:
            newsitem = newsitem_context
        if not is_instance_of_model(newsitem, NewsItem):
            raise template.TemplateSyntaxError(
                "The newsitem argument to 'get_locations_for_item' tag must be either a NewsItem, or a dictionary eg. as created by the template_context_for_item() function"
            )

        # TODO: cache the LocationType lookup?
        location_types = LocationType.objects.filter(
            slug__in=self.loctype_slugs)
        loctype_dict = dict([(d['slug'], d)
                             for d in location_types.values('name', 'slug')])
        result = []
        nilocations = newsitem.location_set.all()
        for slug in self.loctype_slugs:
            loctype = loctype_dict.get(slug)
            if loctype is None:
                continue
            locations = nilocations.filter(location_type__slug=loctype['slug'])
            # Assume there is at most one intersecting location of each type.
            # That will probably be wrong somewhere someday...
            # eg. neighborhoods with fuzzy borders.
            locations = list(locations[:1])
            if locations:
                location = locations[0]
                result.append({
                    'location_slug':
                    location.slug,
                    'location_type_slug':
                    loctype['slug'],
                    'location_type_name':
                    smart_title(loctype['name'], ['ZIP']),
                    'location_name':
                    location.name,
                })

        context[self.varname] = result
        return u''
Exemplo n.º 8
0
    def render(self, context):
        """Puts some information about overlapping locations into context[varname].
        """
        newsitem_context = self.newsitem_context_var.resolve(context)
        if isinstance(newsitem_context, dict):
            newsitem = newsitem_context.get("_item", None)
        else:
            newsitem = newsitem_context
        if not is_instance_of_model(newsitem, NewsItem):
            raise template.TemplateSyntaxError(
                "The newsitem argument to 'get_locations_for_item' tag must be either a NewsItem, or a dictionary eg. as created by the template_context_for_item() function"
            )

        # TODO: cache the LocationType lookup?
        location_types = LocationType.objects.filter(slug__in=self.loctype_slugs)
        loctype_dict = dict([(d["slug"], d) for d in location_types.values("name", "slug")])
        result = []
        nilocations = newsitem.location_set.all()
        for slug in self.loctype_slugs:
            loctype = loctype_dict.get(slug)
            if loctype is None:
                continue
            locations = nilocations.filter(location_type__slug=loctype["slug"])
            # Assume there is at most one intersecting location of each type.
            # That will probably be wrong somewhere someday...
            # eg. neighborhoods with fuzzy borders.
            locations = list(locations[:1])
            if locations:
                location = locations[0]
                result.append(
                    {
                        "location_slug": location.slug,
                        "location_type_slug": loctype["slug"],
                        "location_type_name": smart_title(loctype["name"], ["ZIP"]),
                        "location_name": location.name,
                    }
                )

        context[self.varname] = result
        return u""