在PyCharm中,为什么运行Django项目时的PYTHONPATH与运行manage.py syncdb任务时不同?

1 投票
2 回答
1762 浏览
提问于 2025-04-16 12:51

难道默认情况下不应该是一样的吗?如果不是,有没有什么方法可以解决这个问题,让它使用相同的PYTHONPATH呢?

2 个回答

0

你在设置里选择了适合你项目的Python安装版本吗?路径是:设置 > Python解释器。

1

这可能不是最完美的解决办法,但它确实有效,而且是我老板提供的。

你需要修改一下pycharm里的django_manage.py文件,在所有现有代码之前,最上面插入以下代码。你可以在[PyCharm安装目录]/helpers/pycharm/django_manage.py找到这个文件。

import site
import sys

# Add the locations missing from PYTHONPATH when running a manage.py task here.
ALLDIRS = [
    r'C:\git_repos\src\dev\common\py',
    r'C:\git_repos\src\dev\main_website',
]

# Remember original sys.path.

prev_sys_path = list(sys.path)

# Add each new site-packages directory.

for directory in ALLDIRS:
    site.addsitedir(directory)

# Reorder sys.path so new directories at the front.

new_sys_path = []
for item in list(sys.path):
    if item not in prev_sys_path:
        new_sys_path.append(item)
        sys.path.remove(item)
sys.path[:0] = new_sys_path

撰写回答