2

I am working on a simple web mapping app using Django framework, and I am trying to add a geometric field where to insert polygon geometry's coordinates instead of drawing it manually (these coordinates will be stored in a PostgreSQL database under the column geometry). How to make geom field a coordinates insertion field?

Here is my model class:

from __future__ import unicode_literals
from django.db import models
from django.contrib.gis.db import models as gis_models
from django.db.models import Manager as GeoManager
from django.contrib.gis.geos import Polygon
class projets(models.Model):
     titre = models.CharField(max_length=15)
     avancement = models.CharField(max_length=50,null=True,blank=True)
     geom = gis_models.MultiPolygonField(srid=4326,null=True,blank=True)
     class Meta:
         verbose_name_plural ="Projets"

1 Answer 1

2

You have to follow a couple of steps to achieve your spatial data file imported into database. Geodjango provides an effective tool, LayerMapping utility for converting geometry and field attributes from spatial formats like shapefile.

Steps to follow:

  • Decide where to import and process your file, admin or other views.
  • Write a view and form accepting post request and file in appropriate format (e.g. zip for shapefiles)
  • Check and read file contents, then map field attributes to your model's fields.
  • Create objects if no errors raised.

Below is showing how to create objects from a zipfile containing required files. Keys in the mapping show your model's field names.

from django.contrib.gis.utils.layermapping import LayerMapping
mapping = { 'region':  {'id': 'REGION_ID'},
            'id':'COM_ID',
            'name':'COM_AD',
            'area':'AreaSq',
            'geom':'MULTIPOLYGON',
           }

required_suffixes = ["shp", "shx", "dbf", "prj"]


def validate_shp_files(filelist):

    has_suffix = {}
    for suffix in required_suffixes:
        has_suffix[suffix] = False
    for name in filelist:
        extension = name.split(".")[1].lower()
        if extension in required_suffixes:
            has_suffix[extension] = True
    for suffix in required_suffixes:
        if not has_suffix[suffix]:
            return "{} is missing in zip archive".format(suffix)
    return True



def import_data(zipfile_import):

    validate = validate_shp_files(zipfile_import.namelist())
    if not validate == True:
        return validate    
    try:
        lm = LayerMapping(ModelName, zipfile_import, mapping)
        lm.save(verbose=True)
    except LayerMapError as e:            
        return "Conversion error..."
    

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.