如何将settings.py中的变量传递给视图?

Geu*_*uis 30 django variables

我使用以下命令在settings.py中的Django应用程序中获取项目路径:

PROJECT_PATH = os.path.realpath(os.path.dirname(__file__))
Run Code Online (Sandbox Code Playgroud)

我想在其他视图中使用PROJECT_PATH值,例如在我的静态路径中查找文件的路径.如何将其变为可访问的变量?

And*_*Dog 43

使用from django.conf import settings但记住,settings它不是一个模块.该文件清楚地说明这一点,你的使用情况.


Muh*_*aqi 15

from django.conf import settings
project_path = settings.PROJECT_PATH
Run Code Online (Sandbox Code Playgroud)


oru*_*kin 7

  1. settings.py添加

    DOMAIN = "example.com"
    
    Run Code Online (Sandbox Code Playgroud)
  2. views.py

    from django.conf import settings
    
    DOMAIN = settings.DOMAIN
    
    Run Code Online (Sandbox Code Playgroud)
  3. 让我们尝试output it

    print(DOMAIN)
    
    print(type(DOMAIN))
    
    Run Code Online (Sandbox Code Playgroud)
  4. output will be:

    example.com
    
    <class 'str'>
    
    Run Code Online (Sandbox Code Playgroud)