Search code examples
djangorastergdalgeodjangopostgis-raster

GeoDjango tif import with "Raster needs to be opened in write mode to change values error"


I am trying to import raster file to PostGIS via Django Shell. I create a class in my model, looks like that:

class MaxentModel(gismodels.Model):
    birdname = models.ForeignKey('BirdName', null=True)
    model_probability = gismodels.RasterField(srid=4326, null=True)

Then I want try to import first raster data with these commands from documentation (tried in Django shell):

>>>from validation_birds.models import BirdName, MaxentModel
>>>taxon_name_object = BirdName.objects.filter(name_cz='name of the bird')[0]
>>>rast = MaxentModel(birdname=taxon_name_object, model_probability='/path/to/file/picture.tif')
>>>rast.save()

But with rast.save() exceptions is raised and I get this error:

raise GDALException('Raster needs to be opened in write mode to change values.')
django.contrib.gis.gdal.error.GDALException: Raster needs to be opened in write mode to change values.

What does it mean that raster need to be opened in write mode and why GDAL wants change values (is it because of some setting)? How can I get over this error?

I cannot find some information about this exception so I will be glad for any help


Solution

  • So I found the solution. I was confused by documentation but is needed to create GDALRaster object and this object can be used for RasterField in geodjango. Here is a code:

    >>> from validation_birds.models import BirdName, MaxentModel
    >>> taxon_name_object = BirdName.objects.filter(name_cz='name of the bird')[0]
    >>> from django.contrib.gis.gdal import GDALRaster
    >>> gdal_raster = GDALRaster('pathtofile.tif', write=True)
    >>> rast = MaxentModel(birdname=taxon_name_object, model_probability=gdal_raster)
    >>> rast.save()