django/django · error · GDALException

Cannot create Layer, invalid pointer given

Error message

Cannot create Layer, invalid pointer given

What it means

Raised as GDALException by Layer.__init__ when the OGR layer pointer passed in is null/falsy (layer.py:35). A null pointer means the datasource has no such layer or the layer handle could not be obtained, so Django refuses to wrap it.

Source

Thrown at django/contrib/gis/gdal/layer.py:35

# For more information, see the OGR C API source code:
#  https://gdal.org/api/vector_c_api.html
#
# The OGR_L_* routines are relevant here.
class Layer(GDALBase):
    """
    A class that wraps an OGR Layer, needs to be instantiated from a DataSource
    object.
    """

    def __init__(self, layer_ptr, ds):
        """
        Initialize on an OGR C pointer to the Layer and the `DataSource` object
        that owns this layer. The `DataSource` object is required so that a
        reference to it is kept with this Layer. This prevents garbage
        collection of the `DataSource` while this Layer is still active.
        """
        if not layer_ptr:
            raise GDALException("Cannot create Layer, invalid pointer given")
        self.ptr = layer_ptr
        self._ds = ds
        self._ldefn = capi.get_layer_defn(self._ptr)
        # Does the Layer support random reading?
        self._random_read = self.test_capability(b"RandomRead")

    def __getitem__(self, index):
        "Get the Feature at the specified index."
        if isinstance(index, int):
            # An integer index was given -- we cannot do a check based on the
            # number of features because the beginning and ending feature IDs
            # are not guaranteed to be 0 and len(layer)-1, respectively.
            if index < 0:
                raise IndexError("Negative indices are not allowed on OGR Layers.")
            return self._make_feature(index)
        elif isinstance(index, slice):
            # A slice was given
            start, stop, stride = index.indices(self.num_feat)

View on GitHub (pinned to ae25a40be0)

Solutions

  1. Check DataSource.layer_count and the available layer names before accessing a layer.
  2. Verify the file is a valid OGR-readable vector datasource with `ogrinfo` before opening in Django.
  3. Ensure the file is non-empty and not truncated; re-export from the source if corrupt.
  4. Catch GDALException around DataSource opening and fall back to a clear user-facing error.

Example fix

// before
layer = ds[0]  # may raise if datasource has no layers

// after
if ds.layer_count == 0:
    raise ValueError('Datasource has no layers')
layer = ds[0]
Defensive patterns

Strategy: try-catch

Validate before calling

def open_layer(ds, idx=0):
    if ds.layer_count == 0:
        raise ValueError('datasource has no layers')
    if not (-ds.layer_count <= idx < ds.layer_count):
        raise IndexError(f'layer index {idx} out of range [0,{ds.layer_count})')
    return ds[idx]

Type guard

def datasource_has_layers(ds) -> bool:
    return getattr(ds, 'layer_count', 0) > 0

Try / catch

from django.contrib.gis.gdal import GDALException
try:
    layer = ds[0]
except GDALException:
    raise ValueError('Could not open layer; file may be empty or corrupt') from None

Prevention

When it happens

Trigger: Internally triggered when DataSource.__getitem__/get_layer requests a layer index/name that does not exist in the file, or when the underlying file is empty/corrupt and OGR returns no layer.

Common situations: Opening a shapefile/GeoPackage/GeoJSON that is empty or whose driver failed to register a layer; requesting a layer by name that is misspelled; reading a file with the wrong OGR driver.

Related errors


AI-assisted analysis of django/django@ae25a40be0 (2026-08-06). Data as JSON: /api/errors/c3d66c2649b46a52. Report an issue: GitHub.