{"record":{"id":"c3d66c2649b46a52","repo":"django/django","slug":"cannot-create-layer-invalid-pointer-given","errorCode":null,"errorMessage":"Cannot create Layer, invalid pointer given","messagePattern":"Cannot create Layer, invalid pointer given","errorType":"exception","errorClass":"GDALException","httpStatus":null,"severity":"error","filePath":"django/contrib/gis/gdal/layer.py","lineNumber":35,"sourceCode":"# For more information, see the OGR C API source code:\n#  https://gdal.org/api/vector_c_api.html\n#\n# The OGR_L_* routines are relevant here.\nclass Layer(GDALBase):\n    \"\"\"\n    A class that wraps an OGR Layer, needs to be instantiated from a DataSource\n    object.\n    \"\"\"\n\n    def __init__(self, layer_ptr, ds):\n        \"\"\"\n        Initialize on an OGR C pointer to the Layer and the `DataSource` object\n        that owns this layer. The `DataSource` object is required so that a\n        reference to it is kept with this Layer. This prevents garbage\n        collection of the `DataSource` while this Layer is still active.\n        \"\"\"\n        if not layer_ptr:\n            raise GDALException(\"Cannot create Layer, invalid pointer given\")\n        self.ptr = layer_ptr\n        self._ds = ds\n        self._ldefn = capi.get_layer_defn(self._ptr)\n        # Does the Layer support random reading?\n        self._random_read = self.test_capability(b\"RandomRead\")\n\n    def __getitem__(self, index):\n        \"Get the Feature at the specified index.\"\n        if isinstance(index, int):\n            # An integer index was given -- we cannot do a check based on the\n            # number of features because the beginning and ending feature IDs\n            # are not guaranteed to be 0 and len(layer)-1, respectively.\n            if index < 0:\n                raise IndexError(\"Negative indices are not allowed on OGR Layers.\")\n            return self._make_feature(index)\n        elif isinstance(index, slice):\n            # A slice was given\n            start, stop, stride = index.indices(self.num_feat)","sourceCodeStart":17,"sourceCodeEnd":53,"githubUrl":"https://github.com/django/django/blob/ae25a40be07e8a749edf526df37c93e59d4a22c9/django/contrib/gis/gdal/layer.py#L17-L53","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Check DataSource.layer_count and the available layer names before accessing a layer.","Verify the file is a valid OGR-readable vector datasource with `ogrinfo` before opening in Django.","Ensure the file is non-empty and not truncated; re-export from the source if corrupt.","Catch GDALException around DataSource opening and fall back to a clear user-facing error."],"exampleFix":"// before\nlayer = ds[0]  # may raise if datasource has no layers\n\n// after\nif ds.layer_count == 0:\n    raise ValueError('Datasource has no layers')\nlayer = ds[0]","handlingStrategy":"try-catch","validationCode":"def open_layer(ds, idx=0):\n    if ds.layer_count == 0:\n        raise ValueError('datasource has no layers')\n    if not (-ds.layer_count <= idx < ds.layer_count):\n        raise IndexError(f'layer index {idx} out of range [0,{ds.layer_count})')\n    return ds[idx]","typeGuard":"def datasource_has_layers(ds) -> bool:\n    return getattr(ds, 'layer_count', 0) > 0","tryCatchPattern":"from django.contrib.gis.gdal import GDALException\ntry:\n    layer = ds[0]\nexcept GDALException:\n    raise ValueError('Could not open layer; file may be empty or corrupt') from None","preventionTips":["Check ds.layer_count and available layer names before indexing a DataSource.","Validate the file with `ogrinfo` before opening it in Django.","Wrap DataSource access in try/except GDALException and surface a user-facing error."],"tags":["gis","ogr","datasource","layer","data-corruption"],"analyzedSha":"ae25a40be07e8a749edf526df37c93e59d4a22c9","analyzedAt":"2026-08-06T21:46:51.801Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}