Django: Fuss-free use of Homebrew GDAL/GEOS libraries on macOS

Your brain on GeoDjango.

GeoDjango requires the GDAL and GEOS spatial libraries. On macOS, you can use Homebrew to install these, but they won’t be picked up by default since they live in a non-default library directory, /opt/homebrew/lib. Django will fail to start with an exception:

Traceback (most recent call last):
  ...
  File "/.../site-packages/django/contrib/gis/gdal/libgdal.py", line 60, in <module>
    raise ImproperlyConfigured(
django.core.exceptions.ImproperlyConfigured: Could not find the GDAL library (tried "gdal", "GDAL", "gdal3.4.0", "gdal3.3.0", "gdal3.2.0", "gdal3.1.0", "gdal3.0.0", "gdal2.4.0", "gdal2.3.0", "gdal2.2.0"). Is GDAL installed? If it is, try setting GDAL_LIBRARY_PATH in your settings.

You can follow the message and set GDAL_LIBRARY_PATH, and similarly GEOS_LIBRARY_PATH. But that leaves you with a change in your settings file that you need to be careful not to commit, otherwise it will break the project for other environments. Also it’s a per-project solution, requiring repetitive repetition whenever you encounter the error.

My preferred alternative is to add symlinks in the default library directory, /usr/local/lib, pointing to the Homebrew library location:

$ ln -s /opt/homebrew/lib/libgdal.dylib /usr/local/lib/libgdal.dylib

$ ln -s /opt/homebrew/lib/libgeos_c.dylib /usr/local/lib/libgeos_c.dylib

That’s a once-and-for-all solution that will work for all projects, and persist through upgrades.

dyld library paths

Another option you may see suggested is to set either DYLD_FALLBACK_LIBRARY_PATH or DYLD_LIBRARY_PATH to include the Homebrew library directory:

$ export DYLD_FALLBACK_LIBRARY_PATH=/opt/homebrew/lib

This will work only in some cases. Those environment variables get unset by Apple’s “System Integrity Protection” when launching a subprocess. If you use a tool that wraps Python, such as a launcher or debugger, you might find that Django then can’t find the libraries. So best to avoid this solution.

Fin

May your GeoDjango journey be joyful,

—Adam


Read my book Boost Your Git DX to Git better.


Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Related posts:

Tags: