Django 2.0教程问题:无法访问Django-Admin Shell
Hey there, let's break down why you're running into this settings error and how to fix it quickly!
The Root Cause
The django-admin command is a global Django utility, and it doesn't automatically know where your project's settings file lives. When you tried using django-admin shell without proper configuration, Django can't find the USE_I18N setting (and others) it needs to initialize the shell.
Your previous attempts didn't work for these reasons:
- Calling
settings.configure()in a plain Python shell only sets up a bare-bones default configuration, not your project's actual settings. - When you used
django-admin.py shell --settings=mysite.settings, Django probably couldn't locate themysitemodule because your current working directory wasn't added to Python's path.
The Simplest Fix: Use manage.py Instead
Every Django project comes with a manage.py file in its root directory—this file is pre-configured to point to your project's settings automatically. Here's what to do:
- First, navigate to your project's root directory (the one that contains
manage.py). From your terminal output, it looks like you're inmysite3, but double-check thatmanage.pyis there. - Run this command:
python manage.py shell
This should launch the Django shell without any settings errors, since manage.py handles the DJANGO_SETTINGS_MODULE setup for you.
If You Must Use django-admin shell
If you prefer using django-admin for some reason, you need to explicitly tell Django where your settings are and ensure your project root is in Python's path:
- Set the environment variable for your settings module:
export DJANGO_SETTINGS_MODULE=mysite.settings - Add your project root directory to Python's path (replace the path below with your actual project root):
export PYTHONPATH=/Users/coreydickinson/mysite/DJDev/env2/mysite3 - Now run the shell command:
django-admin shell
You can also combine these into a single command to avoid setting variables every time:
DJANGO_SETTINGS_MODULE=mysite.settings PYTHONPATH=/Users/coreydickinson/mysite/DJDev/env2/mysite3 django-admin shell
Double-Check Your Project Structure
Make sure your project has the standard Django structure, like this:
mysite3/ ├── manage.py └── mysite/ ├── settings.py ├── urls.py └── wsgi.py
If your settings.py is in a different location, adjust the DJANGO_SETTINGS_MODULE value accordingly (e.g., if it's in mysite3/config/settings.py, use config.settings).
内容的提问来源于stack exchange,提问作者StupidQuestionGuy

