13
So as a full answer:
If you use the python package mysqlclient you still need to install the mysql client from Oracle/MySQL. This contains the C-library that the python package uses. To make things more confusing: the python package is in fact written in C for speed increases. To install this library on MacOS:
% brew install mysql-client
Thereโs also a pure python package, with a more attractive MIT License, which can be a solution if your company or client does not allow GPL. However, itโs not officially supported and some subtle bugs can occur in between releases. YMMV.
22
This did the job for me! Just install libmysqlclient-dev (sudo apt-get install libmysqlclient-dev
for Ubuntu). Sometimes, the lib files simply are missing even if you just installed mysql.
- [Django]-Django models avoid duplicates
- [Django]-How can I get all the request headers in Django?
- [Django]-Making a Django form class with a dynamic number of fields
21
this worked for me:
add this to PATH:
export DYLD_LIBRARY_PATH="/usr/local/mysql/lib:$PATH"
- [Django]-Django โ set user permissions when user is automatically created using get_or_create
- [Django]-How to put comments in Django templates?
- [Django]-Implementing Single Sign On (SSO) using Django
19
So, Iโm answering my own question. Since my blog has database, I gave it a shot to make another project without db, start fresh.
What I noticed was thereโs a problem importing MySQLdb
module(sub module of mysqlclient) with this traceback: Library not loaded: @rpath/libmysqlclient.21.dylib
.
For browsing a few hours I realised that for some reason Mac security setting keeps this from being imported properly.
On mysqlclient
library github I found one issue reporting the same as mine. It suggests I run cp -r /usr/local/mysql/lib/* /usr/local/lib/
. After this I set settings.py
for django.db.backends.mysql
, ran python manage.py migrate
and it worked. So for empty database, this could be a solution. Still struggling with database one though.
I use
- MacOS Catalina 10.15.6
- pyenv
- [Django]-SyntaxError: Generator expression must be parenthesized
- [Django]-What are the limitations of Django's ORM?
- [Django]-Converting timezone-aware datetime to local time in Python
15
Make sure you have installed mysql client. To install it write following command.
pip install mysqlclient
Go to the settings.py file of your project and then import
import pymysql
pymysql.install_as_MySQLdb()
run the server
If you get no module named pymysql then in terminal run
pip install pymysql
- [Django]-Django logging of custom management commands
- [Django]-Django: is there a way to count SQL queries from an unit test?
- [Django]-Django 1.9 deprecation warnings app_label
10
I was facing the same problem on my MacOS (Big Sur) and I fixed it by doing this
cp -r /usr/local/mysql/lib/* /usr/local/lib/
- [Django]-Python Django Gmail SMTP setup
- [Django]-How do I stop getting ImportError: Could not import settings 'mofin.settings' when using django with wsgi?
- [Django]-How to get the value of a Django Model Field object
7
On a MacBook Pro M1 macOS Monterey, running this command didnโt work:
export DYLD_LIBRARY_PATH="/usr/local/mysql/lib:$PATH"
But this worked for me:
export DYLD_LIBRARY_PATH=/usr/local/mysql/lib
- [Django]-How to make Django QuerySet bulk delete() more efficient
- [Django]-Django setUpTestData() vs. setUp()
- [Django]-Django : Is it impossible to static tag into block tag?
6
This solved the issue for me:
Since Python3 is not able to connect with Python through mysqldb, you need to install an additional module to fix things. installing mysqlclient caused me to have the same NameError: : name '_mysql' is not defined
problem.
However, by using pymysql
, and adding the code line
pymysql.install_as_MySQLdb()
at the top of my Flask
app, I managed to get it running without any errors!
More info on mysql modules
- [Django]-Set up a scheduled job?
- [Django]-How to check the TEMPLATE_DEBUG flag in a django template?
- [Django]-Redirect to same page after POST method using class based views
2
I had the same error and it was working for a while. I did an update on MacOS BigSur then it stopped working with this error.
To fix this for me it was a simple uninstall reinstall of both django and mysqlclient.
The uninstall/reinstall of just mysqlclient itself did not do the trick. Also the order may help. Here are the commands in the order i did it in:
pip uninstall mysqlclient
pip uninstall django
pip install django
pip install mysqlclient
Note: this will install the latest versions, so if you have specific versions, make sure you install those versions.
- [Django]-Django 2, python 3.4 cannot decode urlsafe_base64_decode(uidb64)
- [Django]-How to view database and schema of django sqlite3 db
- [Django]-Django: Get an object form the DB, or 'None' if nothing matches
2
Iโm using MacOS Sonoma and recently faced this issue.
I installed MySQL using homebrew. I checked the path where mysql was installed using
brew info mysql
Then I noticed that I has libmysqlclient.22.dylib
instead of libmysqlclient.21.dylib
which my app required. I had to create a symbolic link. In my case I had to run
ln -s /opt/homebrew/Cellar/mysql/8.1.0/lib/libmysqlclient.22.dylib /opt/homebrew/Cellar/mysql/8.1.0/lib/libmysqlclient.21.dylib
Afterwards I had to add this to my path and it worked
export DYLD_LIBRARY_PATH="/opt/homebrew/Cellar/mysql/8.1.0/lib:$DYLD_LIBRARY_PATH"
- [Django]-What does "'tests' module incorrectly imported" mean?
- [Django]-SyntaxError: Generator expression must be parenthesized
- [Django]-Django select_for_update cannot be used outside of a transaction
1
I just had a similar problem and couldnt find solution for hours
>>> import MySQLdb
Traceback (most recent call last):
File "/{path-to-venv}/lib/python3.7/site-packages/MySQLdb/__init__.py", line 18, in <module>
from . import _mysql
ImportError: /{path-to-venv}/lib/python3.7/site-packages/MySQLdb/_mysql.cpython-37m-arm-linux-gnueabihf.so: failed to map segment from shared object
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/{path-to-venv}/lib/python3.7/site-packages/MySQLdb/__init__.py", line 24, in <module>
version_info, _mysql.version_info, _mysql.__file__
NameError: name '_mysql' is not defined
so if anyone here is like me and has the virtualenv on a mounted partition/disk, you have to mount it with exec, thats the whole problem.
Remount the partition with executable permission as explained in: https://askubuntu.com/questions/311438/how-to-make-tmp-executable.
If you mount the drive with fstab, see: https://askubuntu.com/questions/678857/fstab-doesnt-mount-with-exec.
(well, that was 10hours of trying and debugging well spend lol)
- [Django]-How to duplicate virtualenv
- [Django]-Python vs C#/.NET โ what are the key differences to consider for using one to develop a large web application?
- [Django]-Change a field in a Django REST Framework ModelSerializer based on the request type?
1
I faced the same issue with my django project working on ubuntu 22.04 but when i imported the code below to the setting file for the django project it works,
- import pymysql
- pymysql.install_as_MySQLdb()
it will only work if you have pymysql installed but if you donโt have it installed used pip install pymysql.
This worked for me
- [Django]-ChoiceField doesn't display an empty label when using a tuple
- [Django]-How to set environment variables in PyCharm?
- [Django]-What is a context in Django?
1
I tried all the solutions listed here and none of them worked for me.
My solution to this was to use a conda environment rather than a virtualenv. Just copy your environment to requirements.txt (for convenience) and make a new environment with conda.
- pip freeze > requirements.txt (save your environment)
- conda create -n django-env โfile requirements.txt (create new environment)
- pip install mysqlclient (if it wasnโt already)
I was able to connect to my local mysql database and also my Amazon RDS database, no problem. I know this doesnโt solve the issue directly. If you absolutely must use virtualenv this wonโt help.
I signed up for a Stackoverflow account just to share this. I hope it saves some other poor soul from 10 hours of "_mysql is not defined" hell.
- [Django]-Alternative to the deprecated setup_environ() for one-off django scripts?
- [Django]-Split views.py in several files
- [Django]-Django-tables2: How to use accessor to bring in foreign columns?
0
I agree with Melvyn.
you can see your MySQL library link by typing like:
(quantum) chaiyudeMacBook-Pro:quantum chaiyu$ python
Python 3.8.7 (v3.8.7:6503f05dd5, Dec 21 2020, 12:45:15)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import MySQLdb as Database
Traceback (most recent call last):
File "/Users/chaiyu/Envs/quantum/lib/python3.8/site-packages/MySQLdb/__init__.py", line 18, in <module>
from . import _mysql
ImportError: dlopen(/Users/chaiyu/Envs/quantum/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so, 2): Library not loaded: /usr/local/opt/mysql/lib/libmysqlclient.21.dylib
Referenced from: /Users/chaiyu/Envs/quantum/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so
Reason: image not found
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/chaiyu/Envs/quantum/lib/python3.8/site-packages/MySQLdb/__init__.py", line 24, in <module>
version_info, _mysql.version_info, _mysql.__file__
NameError: name '_mysql' is not defined
then type:
(quantum) chaiyudeMacBook-Pro:quantum chaiyu$ otool -L /Users/chaiyu/Envs/quantum/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so
/Users/chaiyu/Envs/quantum/lib/python3.8/site-packages/MySQLdb/_mysql.cpython-38-darwin.so:
/usr/local/opt/mysql/lib/libmysqlclient.21.dylib (compatibility version 21.0.0, current version 21.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.250.1)
(quantum) chaiyudeMacBook-Pro:quantum chaiyu$ ls -l /usr/local/opt/mysql/lib/libmysqlclient.21.dylib
ls: /usr/local/opt/mysql/lib/libmysqlclient.21.dylib: No such file or directory
and then, I found the library MySQL linked to does not exist.
- [Django]-How do I create a login API using Django Rest Framework?
- [Django]-Could not find a version that satisfies the requirement pkg-resources==0.0.0
- [Django]-Django-object-permissions Vs django-guardian Vs django-authority
- [Django]-Save base64 image in django file field
- [Django]-Django REST Framework and FileField absolute url
- [Django]-Django Admin: Using a custom widget for only one model field
0
for mac
Assume you are activating Python 3 venv
brew install mysql
pip install mysqlclient
for ubuntu interminal run
sudo apt-get install python3-dev default-libmysqlclient-dev build-essential
pip install mysqlclient
for # Red Hat / CentOS
sudo yum install python3-devel mysql-devel
pip install mysqlclient
- [Django]-Foreign key from one app into another in Django
- [Django]-Is there any difference between django.conf.settings and import settings?
- [Django]-How to find out the request.session sessionid and use it as a variable in Django?
0
Finally after spending like decade on this issue found a good answer.
mysqlclient
is a Python 3 compatible fork of the original Python MySQL driver, MySQLdb
. It still provides a Python module called MySQLdb
. On install, it compiles against either the MariaDB client library or MySQL client library โ whichever one you have installed.
Solution Found Here By Adam(Genius Guy)
- [Django]-Can I call a view from within another view?
- [Django]-How to get GET request values in Django Templates?
- [Django]-Readonly models in Django admin interface?
0
From Apple Silicon M1 Mac and a conda environment the only solution that worked for me was to use Miniforge installation, which is comparable to Miniconda, but with conda-forge as the default channel. There is an Apple Silicon option that solved the problem for me: https://github.com/Haydnspass/miniforge#download
(Solution from https://towardsdatascience.com/using-conda-on-an-m1-mac-b2df5608a141)
- [Django]-Ordering admin.ModelAdmin objects in Django Admin
- [Django]-Creating a model and related models with Inline formsets
- [Django]-How to backup a django db
0
If youโre using bash, use:
open -t .bash_profile
and add the following:
export DYLD_LIBRARY_PATH="/usr/local/mysql/lib:$PATH"
If youโre using Zsh, use:
open -t ~/.zshrc
and add the following:
export DYLD_LIBRARY_PATH="/usr/local/mysql/lib:$PATH"
- [Django]-Cannot import name patterns
- [Django]-How to limit the maximum value of a numeric field in a Django model?
- [Django]-How do I filter ForeignKey choices in a Django ModelForm?
0
although I used _mysql for 10 years, the MySQL website tells the recommended way for Python 3 at:
https://dev.mysql.com/doc/connector-python/en/preface.html
Conversion may take some time, but for me less than an hour. Here an example with new code:
import mysql.connector
cnx = mysql.connector.connect(user='mensfort', password='zhongcan',
host='127.0.0.1', database='restaurant')
cursor = cnx.cursor()
cursor.execute('select dongle from personnel')
for dongle in cursor:
print(dongle)
cursor.close()
cnx.close()
Please use your own password, database name, queries, this is just an example.
Please do UNINSTALL this. This is not working for me:
pip uninstall mysql-connector
Please INSTALL this first. It works great:
pip install mysql-connector-python
- [Django]-Get Timezone from City in Python/Django
- [Django]-Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: Origin checking failed does not match any trusted origins
- [Django]-Django manage.py: Migration applied before its dependency
- [Django]-CORS error while consuming calling REST API with React
- [Django]-Generic many-to-many relationships
- [Django]-The request's session was deleted before the request completed. The user may have logged out in a concurrent request, for example
0
M1 MacBook Pro with Ventura; working fine before then suddenly started getting this error.
TLDR:
brew link mysql-client --force
Iโm not sure exactly why I started receiving this message but it was after I updated Mac OS to Ventura, did some Homebrew upgrades, and also updated Pycharm.
Checking the actual location of libmysqlclient.21.dylib
and where it was being checked for showed that it simply wasnโt checking the correct location.
Adding the correct location to PATH
didnโt fix it.
Copying the files from mysql/lib/
to /usr/local/lib/
would almost certainly fix it because I could see that location was being checked for the required file but that seems like kind of a workaround to me that might cause issues in the futureโฆlike if the package is updated in the future due to a security vulnerability but you donโt notice and donโt re-copy the updated files.
I could see the Homebrew directories were also being checked but Homebrew doesnโt link this package by default. Trying to link it (brew link mysql-client
) showed a warning that this is a keg-only
package and must be linked with --force
.
Double-checking with brew link mysql-client --force --dry-run
showed that the command would simply link the appropriate files and wouldnโt be deleting anything.
So, I thought it would be safe to go ahead and and force link it and it did indeed fix the issue for me.
- [Django]-Django rest-auth allauth registration with email, first and last name, and without username
- [Django]-Django rest framework, use different serializers in the same ModelViewSet
- [Django]-Macros in django templates
- [Django]-Getting model ContentType in migration โ Django 1.7
- [Django]-Trying to parse `request.body` from POST in Django
- [Django]-Automatically create an admin user when running Django's ./manage.py syncdb
- [Django]-How do I output HTML in a message in the new Django messages framework?
- [Django]-Django "Cannot add or update a child row: a foreign key constraint fails"
- [Django]-Django: Add non_field_error from view?
-3
Reverting back from MySQL Server 8.x.x to 5.7.x worked for me.
Django supports MySQL 5.5.x โ 5.7.x. MySQL 8 and later arenโt supported.
Found @ Django Docs
- [Django]-How to execute a GROUP BY โฆ COUNT or SUM in Django ORM?
- [Django]-How to force Django Admin to use select_related?
- [Django]-AssertionError: `HyperlinkedIdentityField` requires the request in the serializer context