gpt4 book ai didi

python - 如何将 Django 设置导入 python 独立脚本

转载 作者:太空宇宙 更新时间:2023-11-04 00:10:04 25 4
gpt4 key购买 nike

我在调用 Django 脚本时遇到困难。这是我目前在我的根目录中所做的:

>>> import os
>>> os.environ['DJANGO_SETTINGS_MODULE'] = 'settings.py'
>>> from django.conf import settings
>>> settings.configure()
>>> settings.DATABASES
{}

settings.DATABASES 不应为空,因此我知道我没有正确初始化项目。我将如何在 django2.1 中执行此操作?我曾经能够使用 import settings 轻松地做到这一点; setup_environ(settings),但现在不是了。

注意:我希望能够从任何目录运行上面的代码。这是一个尝试从 tmp 导入我的项目的示例:

(V) david$ cd /tmp && python

>>> import django
>>> from django.conf import settings
>>> settings.configure()
>>> django.setup()
>>> from users.models import *
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'users'

最佳答案

2.1 文档声明您现在需要使用 setup()。相关片段:

import django
from django.conf import settings

settings.configure()
django.setup()

# Now this script or any imported module can use any part of Django it needs.
from myapp import models

Here is the full documentation.

关于python - 如何将 Django 设置导入 python 独立脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52821825/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com