Giter Club home page Giter Club logo

django-geojson's Introduction

django-geojson

See the documentation for more information.

django-geojson is a set of tools to manipulate GeoJSON with Django >= 3.2:

  • (De)Serializer for (Geo)Django objects, querysets and lists
  • Base views to serve GeoJSON map layers from models
  • GeoJSON model and form fields to avoid spatial database backends (compatible with django-leaflet for map widgets)
Documentation Status https://travis-ci.org/makinacorpus/django-geojson.png?branch=master https://coveralls.io/repos/makinacorpus/django-geojson/badge.png?branch=master

AUTHORS

Version 1.X:

  • Daniel Sokolowski, serializer snippet
  • ozzmo, python 2.6 compatibility

makinacom

LICENSE

Lesser GNU Public License

django-geojson's People

Contributors

abusquets avatar achilleash avatar adamchainz avatar alvinlindstam avatar amarandon avatar bielfrontera avatar coredumperror avatar djcoin avatar fle avatar gagaro avatar gbip avatar george-silva avatar gutard avatar jeffreykog avatar jlesech avatar justinvansteijn avatar kevcooper avatar konstin avatar leplatrem avatar lukasalexanderweber avatar manelclos avatar micrypt avatar scotteadams avatar sikmir avatar tcommandeur avatar tochev avatar tzetter avatar varnerac-ubnt avatar vayel avatar willemarcel avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-geojson's Issues

Properties passed as a tuple won't get added to extras

The docs say you should pass properties as a list, but the example shows passing a tuple. I have a class with a normal and a dynamic property. If I do this:

GeoJSONSerializer().serialize(bfs,properties=('normal_property', 'dynamic_property'))

normal_property will be serialized, but dynamic_property won't. In the end_object function, 'dynamic_property' won't get added to extras, because of the:

elif isinstance(self.properties, list):

Since you can use that list comprehension syntax on tuples, you could change the test to:

elif isinstance(self.properties, list) or isinstance(self.properties, tuple):

The end_object function then works for properties specified as a tuple as well.

'json.encoder' has no attribute 'FLOAT_REPR'

Using python 3.5

Internal Server Error: /data.geojson/2016-8-13/2016-8-14/
Traceback (most recent call last):
  File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.5/site-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.5/site-packages/django/views/generic/base.py", line 68, in view
    return self.dispatch(request, *args, **kwargs)
  File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py", line 67, in _wrapper
    return bound_func(*args, **kwargs)
  File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py", line 149, in _wrapped_view
    response = view_func(request, *args, **kwargs)
  File "/usr/local/lib/python3.5/site-packages/django/utils/decorators.py", line 63, in bound_func
    return func.__get__(self, type(self))(*args2, **kwargs2)
  File "/usr/local/lib/python3.5/site-packages/djgeojson/views.py", line 79, in dispatch
    return super(GeoJSONLayerView, self).dispatch(*args, **kwargs)
  File "/usr/local/lib/python3.5/site-packages/django/views/generic/base.py", line 88, in dispatch
    return handler(request, *args, **kwargs)
  File "/usr/local/lib/python3.5/site-packages/django/views/generic/list.py", line 175, in get
    return self.render_to_response(context)
  File "/usr/local/lib/python3.5/site-packages/djgeojson/views.py", line 69, in render_to_response
    **options)
  File "/usr/local/lib/python3.5/site-packages/djgeojson/serializers.py", line 381, in serialize
    self.end_serialization()
  File "/usr/local/lib/python3.5/site-packages/djgeojson/serializers.py", line 162, in end_serialization
    floatrepr = json.encoder.FLOAT_REPR
AttributeError: module 'json.encoder' has no attribute 'FLOAT_REPR'

I tested replace the line 162 from serializers.py with that from:
floatrepr = lambda o: format(o, '.2f')

and for me fix this error and work good, but need more test.

How to pass properties to the geojsonfeature filter

Hi, I cannot figure out how to pass the properties parameter to the geojsonfeature filter.

With GeoJSONLayerView in urls.py this is easy:

    GeoJSONLayerView.as_view(model=MyModel,
        properties=(
            ['field1', 'field2',]
        )),
        name='myname')

But for my use case I need to filter the model, that's why I have created a view like this:

def mymodel_geojson(request):
object_list = MyModel.objects.all().filter(some_filter_here)
properties= ['field1', 'field2',]
return render_to_response(
'myapp/mytemplate.geojson',
{
'object_list': object_list,
'properties': properties,
}, )

Now in my template, how do I pass the parameters?

{% load geojson_tags %}

{{ object_list|geojsonfeature:"???" }}

According to this it should not be possible to create a filter accepting multiple parameters:
http://stackoverflow.com/questions/420703/how-do-i-add-multiple-arguments-to-my-custom-template-filter-in-a-django-templat

thanks for the great library!

Warning that Django-Leaflet is not available, even when not needed

I'm only using the serializer, which seems to be working quite well, and using Google Maps instead of Leaflet, so there's no reason for me to have django-leaflet installed. However, this is still throwing this warning

/usr/local/lib/python2.7/dist-packages/djgeojson/fields.py:10: UserWarning: `django-leaflet` is not available.
warnings.warn('`django-leaflet` is not available.')

It looks like the import is at the top of fields.py, and the fix would be pretty simple, just check to see if the leaflet functionality is being used before trying to import django-leaflet.

Thanks for the very useful piece of software!

Django 1.10 removes get_all_related_objects and breaks serializer

Using django-geojson with Django 1.10 throws "''Options' object has no attribute 'get_all_related_objects'".

Following Django 1.10's migration docs, serializes.pt L313 should probably read

[f for f in MyModel._meta.get_fields() 
  if (f.one_to_many or f.one_to_one) 
  and f.auto_created and not f.concrete]

However, doing so will raise errors on L350, where field.serialize will fail for ForeinKey and OneToOne fields. Removing the if field.serialize conditions then raises 'OneToOneRel' object has no attribute 'rel'.

Where is this method field.serialize supposed to come from?

Make GeoJSONResponse more flexible.

I'd like to submit a pull request to be able to overwrite get_queryset. Code below, would this be welcome?

def get_geojson_data(self, context):
    # Might even take object_list from context by default
    return self.get_queryset()

def render_to_response(self, context, **response_kwargs):
    """
    Returns a JSON response, transforming 'context' to make the payload.
    """
    serializer = GeoJSONSerializer()
    response = self.response_class(**response_kwargs)
    # Might want to rename this to data
    queryset = self.get_geojson_data(context)

    options = dict(
        properties=self.properties,
        precision=self.precision,
        simplify=self.simplify,
        srid=self.srid,
        geometry_field=self.geometry_field,
        force2d=self.force2d,
        bbox=self.bbox,
        bbox_auto=self.bbox_auto,
        use_natural_keys=self.use_natural_keys,
    )
    serializer.serialize(
        queryset,
        stream=response,
        ensure_ascii=False,
        **options,
    )
    return response

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1622: ordinal not in range(128)

Hi,

I am not able to install this package because of an unicode error:

pip3.4 install --user django-geojson

Collecting django-geojson
Downloading django-geojson-2.8.0.zip
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "", line 20, in
File "/tmp/pip-build-4rkz06py/django-geojson/setup.py", line 15, in
open(os.path.join(here, 'CHANGES')).read(),
File "/usr/local/lib/python3.4/encodings/ascii.py", line 26, in decode
return codecs.ascii_decode(input, self.errors)[0]
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1622: ordinal not in range(128)

Problems running the test suite locally

I'm trying to make a PR for more flexible GeoJSON views, but the there is no description on how to run local tests.

Apparently tox needs all sorts of additional installs. If you could document or automate the process, that would be much appreciated.

Serializer still depends on GDAL?

I encountered a strange issue. On my development machine, everything worked fine. When I tried to run my project on another computer, I suddenly got errors like the following when saving a PointField:

>>> self.pointField = {'type': 'Point', 'coordinates': [lon, lat]}
>>> self.save()
[2016-28-23 20:28:53] ERROR [django.contrib.gis:45] Error creating geometry from value '{
  "type":"Point",
  "coordinates":[
    7.09,
    50.72
  ]
}' (Initializing geometry from JSON input requires GDAL.)

After performing a sudo apt-get install gdal-bin (which also installed a whole bunch of other geospatial libraries), the errors were gone. But the whole point of using django-geojson is that I don't need to install geospatial libraries just to store some Points and have nice Leaflet widgets.

On both computers, Django runs in the same freshly installed Python3-virtualenv:

$ pip freeze
Django==1.9.2
PyYAML==3.11
crispy-forms-foundation==0.5.3
django-crispy-forms==1.6.0
django-geojson==2.9.0
django-leaflet==0.18.0
jsonfield==1.0.3
mysqlclient==1.3.7
pytz==2015.7
six==1.10.0
xlwt==1.0.0

different geom_type

Hi.
I'm just importing geoJSON in DB and in file some time this field is Polygon, some time is MultiPolygon. Import is OK, but when I'm try to change record in Admin interface and save - I've got error like this:
Polygon does not match geometry type
How I can fix it?

Unicode literal compatibility with Python 3.2

django-geojson 2.7.0

Running setup.py install for django-geojson
    File ".../lib/python3.2/site-packages/djgeojson/tests.py", line 605
      u'type': u'FeatureCollection',
            ^
  SyntaxError: invalid syntax

    File ".../lib/python3.2/site-packages/djgeojson/fields.py", line 37
      err_msg = u'%s is not a valid GeoJSON geometry type' % geom_type
                                                         ^
  SyntaxError: invalid syntax

New in python 3.0:
All text is Unicode. String literals no longer support a leading u or U
New in python 3.3:
Support for the unicode legacy literal (u'value') was reintroduced to simplify the maintenance of dual Python 2.x and 3.x codebases. See PEP 414 for more information.

Possible fix: Porting tips->Unicode literals.

How I Can Add Circle Support In Geometry Type

Hi, thank for this libs, it has helped me a lot.

I need have support to save geojson geometry with type is CIRCLE, also need add the control button in the map on the create and edit views.

How i can do it ???

geojson is not a known serialization format.

Settings.py :
SERIALIZATION_MODULES = {'geojson' :'djgeojson.serializers', }

Error is showing after:

python manage.py loaddata stedsnavn.geojson

So it doesn't see serializer.
Django: 1.4.6
Python: 2.6

Warning in 1.7b3

In Django 1.7 beta 3, I'm seeing this:

/Users/sabe/.virtualenvs/astrobiology-beta5/lib/python2.7/site-packages/djgeojson/fields.py:10: UserWarning: `django-leaflet` is not available.
  warnings.warn('`django-leaflet` is not available.')

I have both installed in settings.py.

Thanks!

<Point object at > is not JSON serializable

When i try to save geojson field from django-leaflet from form -
is not JSON serializable
geom = PointField()

def setup_shop(request):
    if request.method == 'POST':
        form = ShopForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponseRedirect('/')
    else:
        form = ShopForm()
    return render(request, 'setup.html', {'form': form})

``

leaflet does not render in admin and form views

Hi,

Thanks for your great job !

I'm facing a strange problem. I've folowed the doc from the github site, installed both django-leaflet, django-geojson and jsonfield, but form are rendered as "JSONTextField" but not as leaflet field.

I use a django 1.7.

Invalid syntax with python 2.6

Hi,
I have a problem after creating the layer view.
The error code is "invalid syntax "
Exception Location: /usr/local/lib/python2.6/dist-packages/djgeojson/views.py in , line 6

It seems the problem is with the line
from .serializers import Serializer as GeoJSONSerializer

I'm running Django 1.3.1.

Any clue ?

Thanks !

'Serializer' object has no attribute 'deserialize'

Thanks for this project. I'm playing around with importing it in the django shell to see how deserialization works on my data.

However, I get 'Serializer' object has no attribute 'deserialize' if I try to import

>>> from djgeojson.serializers import Serializer as GeoJSONSerializer
>>> GeoJSONSerializer().deserialize()

Does this method not exist if I'm running from shell? The documentation is unclear to me.

Low-level serializer. UTF8.

When, i use Low-level serializer, get this mistake:
'utf8' codec can't decode byte 0xa6 in position 14: invalid start byte. You passed in '\x00\x00\x00\x00\x01\x01\x00\x00\x00\x00\x00\x00_\xa6R@\x91\xbc:IoE@' (<type 'str'="">)

pip install fails on debian 8

When installing django-geojson with pip (python 3.5) the installation fails.

Collecting django-geojson==2.9.1 (from -r requirements.txt (line 17))
  Using cached django-geojson-2.9.1.zip
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-zi6lydcz/django-geojson/setup.py", line 15, in <module>
        open(os.path.join(here, 'CHANGES')).read(),
      File "/webapps/datahub-dev/lib/python3.5/encodings/ascii.py", line 26, in decode
        return codecs.ascii_decode(input, self.errors)[0]
    UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 2118: ordinal not in range(128)

I read somewhere that this could be due to a memory problem. However, created a swapfile and it still doesn't work.

Problem trying to use django-geojson without libgeos

For now, django-geojson is keeping dependancies to libgeos (GEOSGeometry, WKBWriter, ...).

I have tried to fix this here: fle@be7d2cc

It seems to work for my use case (juste placing a collection of PointFields on a map).

I'm not sure about importing GeometryField from djgeojson.fields ... What do you think ?

Bye and thanks for your work :)

Properties defined on Models are not showing up via GeoJSONLayerView

I have a @Property defined on my Model that works fine in django shell, but when I attempt to use it with GeoJSONLayerView it does not come through in the data.

models.py

 @property
    def popupContent(self):
        return '<p>Name: {}</p><p>County: {}</p>'.format(
          self.name,
          self.county)

Works fine in Shell

>>> from wa.models import Water
>>> Water.objects.all()[0].popupContent
'<p>Name: Aberdeen Lake</p><p>County: Grays Harbor</p>'

In urls.py I have specified the property

 url(r'^data/$', GeoJSONLayerView.as_view(
        model=Water, 
        properties=('popupContent')
        ), name='data'),

but in my data its not coming through, only the geometry is. If I specify a field like 'name' in properties then those field values work.

image

Maybe this Is this a regression of #31

Thanks

Polygon import error in 1.9

After updating to 1.9 I got:
File "/usr/local/lib/python2.7/dist-packages/djgeojson/views.py", line 6, in
from django.contrib.gis.geos.geometry import Polygon

then I changed to:
from django.contrib.gis.geos import Polygon

and it seems ok.

Alessandro

Cannot use GeoJSON Tile Layer

Hello folks. First of all good work.

I'm trying to use a tile layer, without success.

First of all, this is my model:

@python_2_unicode_compatible
class UF(models.Model):
    """
    Unidades Federativas (Estados) do Brasil
    """
    id_ibge = models.IntegerField(primary_key=True)
    uf = models.CharField(max_length=2)
    nome = models.CharField(max_length=20)
    regiao = models.CharField(max_length=20)
    if MUNICIPIOS_GEO:
        geom = models.MultiPolygonField(srid=SRID, null=True, blank=True)
        objects = models.GeoManager()

    def __str__(self):
        return self.nome

The geometry is in 4674 SRID (I know for know it's not supported, but I can't even get a response from server - I've even created a view in PostgreSQL, transforming this to 900913 and mapping this as model, without success).

There are my url patterns:

# coding: utf-8
from django.conf.urls import patterns, include, url
from djgeojson.views import GeoJSONLayerView, TiledGeoJSONLayerView
from municipios.models import UF

urlpatterns = patterns("",

                       url(r'^uf/(?P<z>\d+)/(?P<x>\d+)/(?P<y>\d+).geojson$', TiledGeoJSONLayerView.as_view(model=UF, properties=["uf", "nome"]), name="uf")
    )

Django is giving me following traceback:

ValueError at /geojson/uf/5/11/17.geojson
need more than 0 values to unpack

I hunted down the view, and the first line of the get_queryset method used this line of code:

self.z, self.x, self.y = map(int, self.args[:3])

What happens is that in this specific case, the z, x and y are no arguments, they are kwarguments. I did a little testing on this, replacing the map call by manually extracting all the values from the kwargs. It got passed, but i started getting erros like:

"Cannot resolve keyword 'intersection' into field. Choices are: geom, id_ibge, municipio, nome, regiao, uf"

This traces down to the trim option. I manually overrode it to be False.

Then I got: 'unicode' object has no attribute 'iterator' - this call seems to be made inside dispatch. After that dispatch, something got wrong in "handle reverse relationship".

I just did this to try trcking the error down and it seems to be related to the already created bug. I even explicited the necessary fields, and they DO NOT include a reverse field.

So, can you guys help me?

Add marker to map dt work anymore...

Hi,

I got a problem, i can't add marker to map with my current code, he works well some week ago, but with no reason and no edit code it just stop to work, dt understand...

  • latest stable version of django-leaflet and django-geojson
  • django 1.7.4
  • Python 3.4

It's just a basic call :

models.py :

class lieu(models.Model):
nom = models.CharField(max_length = 30, null = True)
geom = GeometryField()
description = models.TextField(null = True)
categorie = models.ForeignKey('categorie', null=True, blank=True)
def str(self):
return self.nom

urls.py

url(r'^map/(?P\w+)/?$', getlieux.as_view(),name='getlieu'),

views.py

class getlieux(GeoJSONLayerView):
model = lieu
#properties=('popupContent',)
def get_queryset(self):
return lieu.objects.filter(categorie__nom=self.kwargs['categ'])

javascript :

$('.rem').click(function() {

categ = $(this).text(); 

$.getJSON('/map/' + categ + '/', function (data) {

    marker.addData(data);
}); 

});

I got this with the ajax request, thats looks normal answer :

{"type": "FeatureCollection", "features": [{"properties": {"model": "plan.lieu"}, "type": "Feature", "id": 12, "geometry": {"type": "Point", "coordinates": [0.17282545566558838, 47.282842764549855]}}], "crs": {"properties": {"href": "http://spatialreference.org/ref/epsg/4326/", "type": "proj4"}, "type": "link"}}

At the install of django-geojson i got geos error dependency, so cant load template, i comment these lines in djgeojson/views.py (thx fle post about this) :

from django.contrib.gis.geos.geometry import Polygon

from django.contrib.gis.db.models import PointField

And after that i can load my templates correctly, i dont think that provoc my problem because my code works some week ago with these line commented...

i got an other random error like this :
At my first install of leaflet and djgeojson, i was able to create a point field in django-admin with the leaflet widget admin, but can't edit it, the leaflet.js just freeze my web browser (firefox or chrome), but works with other geometry field. And in a day, without touch anything in the code, without update etc i was able to edit my point field, from this moment i dt got this error anymore.

Thanks for your answer and enjoy my bad english :p

Unable to edit my Field in Admin with django-leaflet

Hî!
I encountered a bug using Python 3.4 and Django 1.8, attempting to use the admin.

my_app.admin.py:

from django.contrib import admin
from leaflet.admin import LeafletGeoAdmin
from .models import Place

admin.site.register(Place, LeafletGeoAdmin)

my_app.models.py:

from djgeojson.fields import PointField
from django.db import models

class Place(models.Model):
    name = models.CharField(max_length=255)
    geom = PointField()

Traceback:

Environment:

Request Method: GET
Request URL: http://localhost:8000/admin/maps/place/add/

Django Version: 1.8.2
Python Version: 3.4.3
Installed Applications:
('django.contrib.admin',
 'django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'leaflet',
 'djgeojson',
 'maps')
Installed Middleware:
('django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.common.CommonMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware',
 'django.middleware.security.SecurityMiddleware')


Traceback:
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/core/handlers/base.py" in get_response
  132.                     response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/contrib/admin/options.py" in wrapper
  616.                 return self.admin_site.admin_view(view)(*args, **kwargs)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/views/decorators/cache.py" in _wrapped_view_func
  57.         response = view_func(request, *args, **kwargs)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/contrib/admin/sites.py" in inner
  233.             return view(request, *args, **kwargs)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/contrib/admin/options.py" in add_view
  1516.         return self.changeform_view(request, None, form_url, extra_context)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapper
  34.             return bound_func(*args, **kwargs)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/utils/decorators.py" in _wrapped_view
  110.                     response = view_func(request, *args, **kwargs)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/utils/decorators.py" in bound_func
  30.                 return func.__get__(self, type(self))(*args2, **kwargs2)
File "/usr/lib/python3.4/contextlib.py" in inner
  30.                 return func(*args, **kwds)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/contrib/admin/options.py" in changeform_view
  1456.         ModelForm = self.get_form(request, obj)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/contrib/admin/options.py" in get_form
  675.             fields = flatten_fieldsets(self.get_fieldsets(request, obj))
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/contrib/admin/options.py" in get_fieldsets
  354.         return [(None, {'fields': self.get_fields(request, obj)})]
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/contrib/admin/options.py" in get_fields
  664.         form = self.get_form(request, obj, fields=None)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/contrib/admin/options.py" in get_form
  700.             return modelform_factory(self.model, **defaults)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/forms/models.py" in modelform_factory
  545.     return type(form)(class_name, (form,), form_class_attrs)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/forms/models.py" in __new__
  285.                                       opts.help_texts, opts.error_messages)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/forms/models.py" in fields_for_model
  216.             formfield = formfield_callback(f, **kwargs)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/leaflet/admin.py" in formfield_for_dbfield
  41.             return db_field.formfield(**kwargs)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/djgeojson/fields.py" in formfield
  65.         return super(GeoJSONField, self).formfield(**kwargs)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/jsonfield/fields.py" in formfield
  48.         return super(JSONField, self).formfield(**defaults)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/db/models/fields/__init__.py" in formfield
  912.         return form_class(**defaults)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/jsonfield/forms.py" in __init__
  15.         super(JSONFormField, self).__init__(*args, **kwargs)
File "/home/batisteo/.virtualenvs/env/lib/python3.4/site-packages/django/forms/fields.py" in __init__
  214.         super(CharField, self).__init__(*args, **kwargs)

Exception Type: TypeError at /admin/maps/place/add/
Exception Value: __init__() got an unexpected keyword argument 'geom_type'

I was able to work around this issue by commenting the formfield() method, in fields.py:63:

class GeoJSONField(JSONField):
    description = _("Geometry as GeoJSON")
    form_class = GeoJSONFormField
    dim = 2
    geom_type = 'GEOMETRY'

    # def formfield(self, **kwargs):
        # kwargs.setdefault('geom_type', self.geom_type)
        # return super(GeoJSONField, self).formfield(**kwargs)

It seems the geom_type is correctly taken in the FormField. So, what is the point of this method?

django-geojson produces empty geojson file

I tried django-geojson on some data I have with Django 1.4:

./manage.py dumpdata --format=geojson yourapp.Model > export.geojson

But the geojson file is empty. My geometry is stored in a column called "the_geom".

Cannot initialize on empty sequence.

I have a geo object with no coordinates yet. When I try to read an empty geo, I thought it would return an empty geojson feature or no feature for that object, but i get the following stack trace:

Internal Server Error: /geodata
Traceback (most recent call last):
File "/home/me/Desktop/projects/testproject/env/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "/home/me/Desktop/projects/testproject/env/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 147, in get_response
response = wrapped_callback(request, _callback_args, *_callback_kwargs)
File "/home/me/Desktop/projects/testproject/env/local/lib/python2.7/site-packages/django/views/generic/base.py", line 68, in view
return self.dispatch(request, _args, *_kwargs)
File "/home/me/Desktop/projects/testproject/env/local/lib/python2.7/site-packages/django/utils/decorators.py", line 67, in _wrapper
return bound_func(_args, *_kwargs)
File "/home/me/Desktop/projects/testproject/env/local/lib/python2.7/site-packages/django/utils/decorators.py", line 149, in _wrapped_view
response = view_func(request, _args, *_kwargs)
File "/home/me/Desktop/projects/testproject/env/local/lib/python2.7/site-packages/django/utils/decorators.py", line 63, in bound_func
return func.get(self, type(self))(_args2, *_kwargs2)
File "/home/me/Desktop/projects/testproject/mysite/maptacs/views.py", line 53, in dispatch
return super(GeoJSONLayerView, self).dispatch(_args, *_kwargs)
File "/home/me/Desktop/projects/testproject/env/local/lib/python2.7/site-packages/django/views/generic/base.py", line 88, in dispatch
return handler(request, _args, *_kwargs)
File "/home/me/Desktop/projects/testproject/mysite/maptacs/views.py", line 87, in post
**options)
File "/home/me/Desktop/projects/testproject/env/local/lib/python2.7/site-packages/djgeojson/serializers.py", line 379, in serialize
self.serialize_queryset(queryset)
File "/home/me/Desktop/projects/testproject/env/local/lib/python2.7/site-packages/djgeojson/serializers.py", line 320, in serialize_queryset
self.handle_field(obj, self.geometry_field)
File "/home/me/Desktop/projects/testproject/env/local/lib/python2.7/site-packages/djgeojson/serializers.py", line 212, in handle_field
value = getattr(obj, field_name)
File "/home/me/Desktop/projects/testproject/mysite/maptacs/models.py", line 81, in geom
return LineString(allpoints)
File "/home/me/Desktop/projects/testproject/env/local/lib/python2.7/site-packages/django/contrib/gis/geos/linestring.py", line 42, in init
raise TypeError('Cannot initialize on empty sequence.')
TypeError: Cannot initialize on empty sequence.

Looks like this is in the serializer.serialize function.

Version bump

Would you be willing to bump the minor version and push to 2.6.1? This would make it easy use the with_modelname functionality via a pip install of django-geojson.

Dynamic properties are not serialized for object list

Take a class with a dynamic a property :

class MushroomSpot(models.Model):
    @property
    def foo(self):
        return 'foo'

If you use geojsonfeature with something other than a queryset (object, object list), like that:

{{ mushroomspot_list|geojsonfeature:"foo"|safe }};
or
{{ mushroomspot|geojsonfeature:"foo"|safe }};

MushroomSpot.foo is not serialized in feature properties.

I think this is because in this case, you transform objects as dict (with model_to_dict) and therefore the code below in Serializer.end_object doesn't work:

        for field in extras:
            if hasattr_lazy(obj, field):    #  Always False if obj is a dict
                self.handle_field(obj, field)

Maybe you can add fields declared in properties to the dict created with model_to_dict in Serializer.serialize_object_list. Something like: fle@07e5881

Sadly, I couldn't write a test because I do not use libgeos ...

Problem serializing a model class with a foreign field

Hello,

I'm struggling with a problem using this plugin, serializing to GeoJSON a simple model class (call it A) with a Polygon.

The problem is another model class (call it B) contains a foreign key to A, and the serializer throws an error, because it tries to find one of the B fields in A. Of course, it isn't found.

May it be a bug on the serializer?

Extended information about the problem here

Don't serialize fields from ForeignKey definition

When i try to serialize fields from ForeignKey definition I receive the following warnings:

serializers.py:312: RemovedInDjango110Warning: 'get_all_related_objects is an unofficial API that has been deprecated. You may be able to replace it with 'get_fields()'
reversed_fields = [obj.field for obj in opts.get_all_related_objects()]

serializers.py:313: RemovedInDjango110Warning: 'get_all_related_many_to_many_objects is an unofficial API that has been deprecated. You may be able to replace it with 'get_fields()'
reversed_fields += [obj.field for obj in opts.get_all_related_many_to_many_objects()]

Serialising related objects

Hi. I'm having trouble serialising a related object as it is not serialisable.

I know it is not really a bug, but I can't see how to specify how to serialise related objects. Perhaps the docs could be expanded to explain how it is done, or if it is not supported, then to say so?

Thanks

Problem using serializer with Dumpdata

When I run dumpdata with geojson it doesn't detect any features.

Looked into it a bit and dumpdata passes a generator object to the serialize methods, and this serializer seems to expect queryset-like objects.

GeoJSONLayerView and LoginRequiredMixin

Hi,

I'm using GeoJSONLayerView in my project. While I am using GeoJSONLayerView in my urls.py, it works.
My views.py:

from django.contrib.auth.mixins import LoginRequiredMixin
from djgeojson.views import GeoJSONLayerView, TiledGeoJSONLayerView

class GeoJSONData (LoginRequiredMixin, GeoJSONLayerView):
    pass

class TiledGeoJSONData (LoginRequiredMixin, TiledGeoJSONLayerView):
    pass

My urls.py

# -*- coding: utf-8 -*-
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from djgeojson.views import TiledGeoJSONLayerView, GeoJSONLayerView

from sights.models import Place, Territory, Municipality
from .views import GeoJSONData, TiledGeoJSONData

urlpatterns = [
    # url(r'^place.geojson$', GeoJSONLayerView.as_view(model=Place, properties=('name', 'pk', 'municipality')),
    #     name='geodata_place'),
    url(r'^place.geojson$', GeoJSONData.as_view(model=Place, properties=('name', 'pk', 'municipality')),
        name='geodata_place'),
    url(r'^place/(?P<z>\d+)/(?P<x>\d+)/(?P<y>\d+).geojson$',
        TiledGeoJSONData.as_view(model=Place, trim_to_boundary=True, properties=('name', 'pk', 'municipality')),
        name='geodata_place_tile'),
    url(r'^municipality.geojson$', login_required(
        GeoJSONLayerView.as_view(model=Municipality, precision=3, simplify=0.5, properties=('name', 'code'))),
        name='geodata_municipality'),
    url(r'^territory.geojson$', login_required(
        GeoJSONLayerView.as_view(model=Territory, precision=3, simplify=0.5, properties=('name', 'code'))),
        name='geodata_territory'),
]

My template:

{% extends 'base_leaflet.html' %}
{% load leaflet_tags %}
{% leaflet_js %}
{% leaflet_css %}
{% load geojson_tags %}
{% block content %}
    <h1><i class="fi-map"></i> Carte des localités</h1>
    {% leaflet_map "main" %}
    <br/>
    <script type="text/javascript">
                var dataurl = '{% url "geodata_place" %}';
                window.addEventListener("map:init", function (event) {
                    var markers = L.markerClusterGroup();
                    var map = event.detail.map;
                    // Download GeoJSON data with Ajax
                    fetch(dataurl)
                        .then(function (resp) {
                            return resp.json();
                        })
                        .then(function (data) {
                            markers.addLayer(L.geoJson(data, {
                                onEachFeature: function onEachFeature(feature, layer) {
                                    var props = feature.properties;
                                    var content = `<h4>${props.pk}${props.name}</h4>
        		                				<p>${props.municipality}</p>
        		                				<p><a class="button" align="center" style="color:white;" href="/place/${props.pk}/detail" target="_blank" style="font-color:white"><strong>Détails</strong></a></p>`;
                                    layer.bindPopup(content);
                                }
                            })).addTo(map);
                        });
                    map.fitBounds(markers.getBounds());
                    map.addControl(new L.Control.Fullscreen());
                });


    </script>
{% endblock %}

But when i'm trying to use LoginRequiredMixin with GeoJSONLayerView, I can't get data on the map where as i can read my geojson data directly in my browser.
Any explanation?
Thanks.

help with binding popup to marker

I'm trying to bind popup window to every marker on map with some data from models (in django-leaflet).
I get data with:

url(r'^quickmap.geojson$', GeoJSONLayerView.as_view(model=Quickpoint, properties=('address' )), name='quickdata')

All data are send to browser correctly, i checked with Firebug in Firefox.

I create map with:

    {% leaflet_map "main" callback="main_map_init" %}

    <script type="text/javascript">
        function main_map_init (map, options) {
            var dataurl = '{% url "quickdata" %}';
            $.getJSON(dataurl, function (data) {
                L.geoJson(data).addTo(map);
            });
        }
    </script>

Map is rendered, all markers placed on map.
Now I tried bind popup with:

{% load geojson_tags %}
...
var divNode = document.createElement('DIV');
divNode.innerHTML = '<div>{{ object|geojsonfeature:"address" }}</div>';
L.geoJson(data).addTo(map).bindPopup(divNode);
...

but always get "null" in binded popup window, instead of address value.
Now i'm confused and not sure, how to get things to work.

Initializing geometry from JSON input requires GDAL.

When try add point from form have error.But when i use for this admin all ok.
Error creating geometry from value '{"type":"Point","coordinates":[30.07718706096056,15.14265066147521]}' (Initializing geometry from JSON input requires GDAL.)

Django-Geojson Test Failure on Django 5.1.2

Functionally the app works as expected, but when i run the tests.py file 8 of the tests fail. Looking into the problem it looks like the TestCases are setting up improperly so that the id autofield for Range objects is being stored with an offset (e.g. the first "saved" Range instance of a TestCase will receive an id of '3' instead of the expected '1', making the assert true test fail when the json is serialized/deserialized).

TravisCI is showing a successful build of django-geojson with Django version 5.1.1, but I am using Django version 5.1.2 so I suspect the problem might be with Django's newer version. I am going to look further into the problem but wanted to give you the heads up in case you are considering upgrading to 5.1.2 in the near future.

Python 3?

Do you have plans to support python3?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.