Error when running custom manage.py command
I'm building a multitenant app based on this page https://www.section.io/engineering-education/implement-multitenancy-with-multiple-databases-in-django/#use-middlewares-for-tenant-specific-database-routing.
It asks to create a custom manage.py (named myapp_manage.py) to create a superuser, so that way I can point the database that I want to run the command like this:
python myapp_manage.py databasename createsuperuser --database=databasename
Everything was ok, I could run the command without problems, but now, when I try to run it, it gives me an error:
django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
I don't understand why this error is showing because the environment in custom manage.py is configured exactly like the standard manage.py.
Custom manage.py:
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
from myapp.middleware import set_db_for_router
if __name__ == "__main__":
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'al_project.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
# new
from django.db import connection
args = sys.argv
db = args[1]
with connection.cursor() as cursor:
set_db_for_router(db)
del args[1]
execute_from_command_line(args)
Standard manage.py:
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'al_project.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ImportError(
"Couldn't import Django. Are you sure it's installed and "
"available on your PYTHONPATH environment variable? Did you "
"forget to activate a virtual environment?"
) from exc
execute_from_command_line(sys.argv)
So, the line 'os.environ.setdefault' is the same in both files and I can run manage.py commands without any issues, which I understand is indication that the path to the file is correct, but I can't run the myapp_manage.py command (the file is located in the same path as the manage.py file).
I did update Django yesterday, but executed the command today for the first time with no problems. The second time that I tried, I received the error. What could be wrong?