pythonmysqldjangomysql-python

Django Python: AttributeError: 'NoneType' object has no attribute 'startswith'


I bumped into the error when running python3 manage.py runserver.

I have mydb.py in the project's root directory (same as manage.py), in order to connect to MySQL and create a database (if it does not exist).

project    
│
└───todo
│   │   ...
│   │   settings.py
│   │   ...
│   
└───.env
└───mydb.py
└───...

mydb.py and settings.py share same database configuration which is loaded from environment variables in .env.

.env:

ENV=DEV
SECRET_KEY='django-insecure-9#1j%osjd33e'
DB_NAME=todolist
DB_USER=user
DB_PASSWORD=12345
DB_HOST=localhost
DB_PORT=3306

settings.py:

import os
from os.path import join, dirname
from dotenv import load_dotenv, find_dotenv

# (1)
ENV = os.environ.get('ENV')

if ENV == 'PROD':
    env_filename = '.env.prod'
elif ENV == 'TEST':
    env_filename = '.env.test'
# elif ENV == 'DEV':
#     env_filename = '.env.dev'
else:
    env_filename = '.env'

dotenv_path = join(dirname(__file__), env_filename)
load_dotenv(dotenv_path)

...

# Database
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': os.environ.get('DB_NAME'),
        'USER': os.environ.get('DB_USER'),
        'PASSWORD': os.environ.get('DB_PASSWORD'),
        'HOST': os.environ.get('DB_HOST'),
        'PORT': os.environ.get('DB_PORT'),
    }
}

...

mydb.py:

import mysql.connector

import os
from os.path import join, dirname
from dotenv import load_dotenv, find_dotenv

ENV = os.environ.get('ENV')

if ENV == 'PROD':
    env_filename = '.env.prod'
elif ENV == 'TEST':
    env_filename = '.env.test'
# elif ENV == 'DEV':
#     env_filename = '.env.dev'
else:
    env_filename = '.env'

dotenv_path = join(dirname(__file__), env_filename)
load_dotenv(dotenv_path)

dataBase = mysql.connector.connect(
    host = os.environ.get('DB_HOST'),
    user = os.environ.get('DB_USER'),
    passwd = os.environ.get('DB_PASSWORD'),
)

dataBase = mysql.connector.connect()
...

Problem:

I keep getting the following error, even though DB_HOST is already set in .env.

...
File "/home/user/django-test/.venv/lib/python3.10/site-packages/django/db/backends/mysql/base.py", line 218, in get_connection_params
    if settings_dict["HOST"].startswith("/"):
AttributeError: 'NoneType' object has no attribute 'startswith'

I have checked AttributeError: 'NoneType' object has no attribute 'startswith' while makemigrations with manage.py in django and some other related questions, but did not find any help.

Thank you


Solution

  • The problem is likely this:

    join(dirname(__file__), env_filename)
    

    This is in todo/settings.py, so will look for todo/.env.

    You need to go up one more directory.