Search code examples
pythondjangomariadbaccess-denied

django.db.utils.OperationalError: (1045, Access denied for user '<user>'@'localhost'


I can't get my Django project to load my database correctly. It throws this error.

I'm running MariaDB with Django, and I uninstalled all MySQL

I added the user by running:

create database foo_db;
create user foo_user identified by 'foo_password';
grant all on foo_db.* to 'foo_user'@'%';
flush privileges;

as suggested by this post.

The console is throwing me this error back when I try to run ./manage.py runserver

django.db.utils.OperationalError: (1045, "Access denied for user '<user>'@'localhost' (using password: YES)")

I have run the 'create user' command and created the user to match my setup script, which has the default set as:

        'ENGINE': 'django.contrib.gis.db.backends.mysql',
        'NAME': 'company_production',
        'USER': 'companydev',
        'PASSWORD': 'companydevpass',
        'HOST': 'localhost',
        'PORT': '',
        'ATOMIC_REQUESTS': True

I have tried everything I've been able to find on here related to the error its thrown, but nothing has been working.

I'm running Mac OSX 10.11.1 El Capitan and MariaDB version 10.1.8 if that's relevant at all.


Solution

  • This is what I use to re-create MySQL databases for Django projects:

    tmp="/tmp/mysql-tools.sh.tmp"
    
    setup-db ( ) {
        cat <<EOF > $tmp
    DROP DATABASE $DB;
    CREATE DATABASE $DB;
    GRANT USAGE on *.* to '${DB_USER}'@'localhost' IDENTIFIED BY '${DB_PASS}';
    GRANT ALL PRIVILEGES ON ${DB}.* to '${DB_USER}'@'localhost';
    EOF
        cat $tmp
        mysql -f -u ${MYSQL_ROOTUSR} -p${MYSQL_ROOTPWD} < $tmp
        rm $tmp
    }
    

    Warning: this drops and re-creates!

    Where:

    • DB: the database name
    • DB_USER: the django database user
    • DB_PASS: the password for the mysql connection for the Django database user
    • MYSQL_ROOTUSR: the mysql root user (must have permissions to create databases)
    • MYSQL_ROOTPWD: the mysql root password

    Export those in your environment