如何获取未在我的 settings.py 文件中定义的 django 默认设置值?
我一定是错过了什么。
我正在尝试从设置文件导入 DEFAULT_CONTENT_TYPE。 我没有在 settings.py 文件中专门定义它,但我假设默认值可用。
当我将此变量添加到我的 settings.py 中时,它工作正常,但是当它不存在并且我尝试导入时,通过 runserver 命令使用开发服务器时,我得到一个 ImportError:
from settings import DEFAULT_CONTENT_TYPE
ImportError: cannot import name DEFAULT_CONTENT_TYPE
我不应该能够做到这一点吗?将其添加到我的 settings.py 文件中吗?
I must be missing something.
I'm trying to import DEFAULT_CONTENT_TYPE from the settings file.
I don't define it specifically in my settings.py file, but I was assuming that the default would be available.
When I add this variable to my settings.py it works fine, but when it's not there and I try to import I get an ImportError when using the development server via the runserver command:
from settings import DEFAULT_CONTENT_TYPE
ImportError: cannot import name DEFAULT_CONTENT_TYPE
Shouldn't I be able to do this without having to add it to my settings.py file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
切勿使用
from settings import ...
或import settings
。这将始终只导入您的设置模块,而不是整个 Django 设置。在所有 Django 项目中使用
from django.conf import settings
代替。这是使用 Django Settings 类,它是所有 Django 定义的设置和设置文件中的项目设置的包装器。因此,对于您的示例,您将通过
settings.DEFAULT_CONTENT_TYPE
访问DEFAULT_CONTENT_TYPE
。Never user
from settings import ...
orimport settings
. This will always only import your settings module, but not the whole Django settings.Use
from django.conf import settings
instead in all your Django projects. This is using the Django Settings class which is a wrapper around all Django defined settings and your project settings from your settings file.So for your example you would access
DEFAULT_CONTENT_TYPE
viasettings.DEFAULT_CONTENT_TYPE
.settings
与您的项目相关,因此它会尝试从您的设置文件导入DEFAULT_CONTENT_TYPE
。如果你想使用 Django 的内置DEFAULT_CONTENT_TYPE
设置,你必须从它们的库中包含它(抱歉,这台机器上没有安装 Django,否则我会查找该文件它是在)中定义的。像这样的东西:
from django.some.settings.file import DEFAULT_CONTENT_TYPE
您应该能够通过 Django lib 目录中的
grep
找到它。settings
is relative to your project, so it'll try to importDEFAULT_CONTENT_TYPE
from your settings file. If you want to use Django's built-inDEFAULT_CONTENT_TYPE
setting, you'd have to include it from their libraries (sorry, don't have Django installed on this machine, otherwise I'd look up the file that it's defined in).Something like this:
from django.some.settings.file import DEFAULT_CONTENT_TYPE
You should be able to find it by just
grep
'ing through your Django lib dir.