简体   繁体   English

如何在 Django 项目的任何位置获取任何脚本的 BASE_DIR?

[英]how can you get your BASE_DIR for any script in any location in Django project?

I can import BASE_DIR in the shell as follows:我可以在 shell 中导入 BASE_DIR,如下所示:

In [3]: from scriptcitymirror.settings import BASE_DIR

In [4]: BASE_DIR
Out[4]: '/home/cchilders/projects/django_practice/scriptcity_public'

but in the script that writes the app for me, I cannot import the exact same thing:但是在为我编写应用程序的脚本中,我无法导入完全相同的东西:

#!/usr/bin/env python

import os, subprocess, sys, re, requests, time
from scriptcitymirror.settings import BASE_DIR

blows up as:炸毁为:

cchilders@cody_pc:~/projects/django_practice/scriptcity_public$ robots/app_writer.py 
Traceback (most recent call last):
  File "robots/app_writer.py", line 4, in <module>
    from scriptcitymirror.settings import BASE_DIR
ImportError: No module named scriptcitymirror.settings

I'm stunned.我惊呆了。 Also, a way I usually do it the main directory (the urls.py file in the dir with settings.py), did not work:另外,我通常在主目录(带有 settings.py 的目录中的 urls.py 文件)的方法不起作用:

from django.conf import settings
settings.configure()

print settings.MEDIA_URL

Right now my ugly work around is calling CWD=os.getcwd() and requiring the script to by run from the home project path.现在我丑陋的解决方法是调用CWD=os.getcwd()并要求脚本从主项目路径运行。 My folders look like the following pic.我的文件夹如下图所示。 How can get BASE_DIR correctly anywhere within django project?如何在 django 项目中的任何地方正确获取 BASE_DIR? (but here, I want to use them in 'robots', which is not an app. the import did not work after making a test app either). (但在这里,我想在“机器人”中使用它们,这不是应用程序。在制作测试应用程序后导入也不起作用)。 Thank you谢谢

在此处输入图像描述

First of all, you should not import your project's settings because it will be missing default settings.首先,您不应该导入项目的settings ,因为它会丢失默认设置。 So, in order to get all the settings you should always import django.conf.settings .因此,为了获得所有设置,您应该始终导入django.conf.settings

Second, Django docs say django.conf.settings is not a module - it's an object.其次,Django 文档说django.conf.settings不是一个模块——它是一个对象。 So you can't import individual settings.所以你不能导入个人设置。

# WRONG way (will not work)
from django.conf.settings import BASE_DIR


# CORRECT way
from django.conf import settings
base_dir = settings.BASE_DIR

See this page: Using settings in Python code请参阅此页面: 在 Python 代码中使用设置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM