Pages

Thursday, July 23, 2020

How to fix the Library not loaded: @rpath/libmysqlclient.21.dylib error in Django for Mac users



There seems to be some problems with macOS Mojave and Catalina users when trying to connect a Django project to a MySQL database.

ImportError: dlopen(..._mysql.cpython-38-darwin.so, 2): Library not loaded: @rpath/libmysqlclient.21.dylib
  Referenced from: .../site-packages/_mysql.cpython-38-darwin.so
  Reason: image not found
NameError: name '_mysql' is not defined

Python seems to be unable to resolve the path to libmysqlclient.21.dylib. One solution is to create a symlink to libmysqlclient.21.dylib in either /usr/local/lib/ or /usr/lib/. You can do so by running this in Terminal:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.21.dylib /usr/local/lib/libmysqlclient.21.dylib

But this doesn't always seem to work. Another solution is to change the path to libmysqlclient.21.dylib specified in _mysql.cpython-38-darwin.so (could be 37 or some other number depending on your Python version). Change it to an absolute path that points to  /usr/local/mysql/lib/libmysqlclient.21.dylib.

_mysql.cpython-38-darwin.so can be found in the MySQLdb directory in site-packages. You can use some Xcode command line tools to fix this. Open a terminal window in the directory that contains _mysql.cpython-38-darwin.so and perform the following:

To check the path:
otool -L _mysql.cpython-38-darwin.so

It's the relative path that seems to be problematic. Command above should output something like this:
_mysql.cpython-38-darwin.so:
    @rpath/libmysqlclient.21.dylib (compatibility version 21.0.0, current version 21.0.0)

Change the relative path to absolute by running this:
install_name_tool -change @rpath/libmysqlclient.21.dylib /usr/local/mysql/lib/libmysqlclient.21.dylib _mysql.cpython-38-darwin.so