djangoserializationpostgisgeojsongeodjango

Geojason serializer is giving null geometry


I'm having the same issue found in this question, though it was supposedly fixed in Django 1.9, so I thought maybe I'm doing something wrong.

I'm trying to serialize my geodjango data:

homes = serialize(
    "geojson",
    Home.objects.all(),
    geometry_field="point",
    fields=["address_point"],
)

I then go to print it out, and it shows that the geometry is null as follows:

{
   "type":"FeatureCollection",
   "crs":{
      "type":"name",
      "properties":{
         "name":"EPSG:4326"
      }
   },
   "features":[
      {
         "type":"Feature",
         "id":1,
         "properties":{
            "address_point":"SRID=4326;POINT (15.57385209377286 7.776164310995906)"
         },
         "geometry":null
      }
   ]
}

Further, when I try to access the data in my javascript (using django-geojson) and then log it to the console, the result is null. I believe the two issues are related.

{% load geojson_tags %}

var homes = {{ homes|geojsonfeature|safe }};
console.log(homes) // null

Would appreciate any insight into fixing this, thank you!

P.S. Results of pip freeze

asgiref==3.8.1
black==24.4.2
certifi==2024.6.2
charset-normalizer==3.3.2
click==8.1.7
Django==5.0.6
django-countries-plus==2.2.0
django-environ==0.11.2
django-geojson==4.1.0
django-languages-plus==2.1.1
django-safedelete==1.4.0
idna==3.7
isort==5.13.2
mypy-extensions==1.0.0
packaging==24.1
pathspec==0.12.1
pillow==10.3.0
platformdirs==4.2.2
psycopg2-binary==2.9.9
requests==2.32.3
setuptools==69.5.1
sqlparse==0.5.0
urllib3==2.2.2
wheel==0.43.0

Edit: Adding model

from django.contrib.auth.models import User
from django.contrib.gis.db import models as gis_models
from django.contrib.gis.geos import Point
from django.db import models

# Just a basic model with created_at and deleted_at
from WebApp.models.base_model import BaseModel 

class Home(BaseModel):
    user = models.ForeignKey(User, on_delete=models.DO_NOTHING)
    address = models.CharField(max_length=256)
    address_point = gis_models.PointField(srid=4326, default=Point(0, 0))
    description = models.TextField()

Solution

  • I have a partial answer: My geometry field should be address_point, so I now have:

    def map(request):
        template_name = "map.html"
        homes = serialize(
            "geojson",
            Home.objects.all(),
            geometry_field="address_point",
            fields=[],
        )
        context = {"homes": homes}
        return render(request, template_name, context)
    

    This now prints properly as have geomerty. However, I have yet to figure out how to get it to display on my map. Still working on that.

    Edit:

    Fully solved without using any libraries or anything beyond simple leafletjs. I now have the following code in my .html file:

            let homes = JSON.parse('{{ homes|safe }}')
            L.geoJson(homes).addTo(map);