我试图在django项目启动时创建html文件,方法是在project / settings.py中包含如下代码:
def Brander():
import configparser
config = configparser.ConfigParser()
config.read('settings.ini')
version = config['PROJECT']['version']
APPNAME = config['BRANDING']['appname']
APPCOMPANY = config['BRANDING']['appcompany']
APPCOMPANYLINK = config['BRANDING']['appcompanysite']
APPLINK = config['BRANDING']['appsite']
from django.contrib.staticfiles import finders
filen = finders.find('clinic/brandedfooter.html')
f = open(filen, "w")
s = f"""
<div class="col-lg-8 col-md-8 d-none d-md-block d-lg-block">
<span class="text-muted float-right"><i>My OP and IP Clinic - <a href="{APPLINK}">{APPCOMPANY} by </a><a href="{APPCOMPANYLINK}">{APPCOMPANY}</a></i></span>
</div>
"""
f.write(s)
我的项目/settings.ini包含:
[PROJECT]
version = 0.0.1
[BRANDING]
appname = MyOPIP
appcompany = Droidzone
appcompanysite = https://droidzone.in
appsite = https://myopip.com
当以上代码作为独立的python脚本运行时,一切正常,并且生成了html文件。但是,当将其作为manage.py runserver
的一部分执行时,出现以下错误:
joel@hp:~/myappointments$ ./manage.py runserver
Traceback (most recent call last):
File "./manage.py", line 15, in <module>
execute_from_command_line(sys.argv)
File "/home/joel/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line
utility.execute()
File "/home/joel/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 325, in execute
settings.INSTALLED_APPS
File "/home/joel/.local/lib/python3.6/site-packages/django/conf/__init__.py", line 57, in __getattr__
self._setup(name)
File "/home/joel/.local/lib/python3.6/site-packages/django/conf/__init__.py", line 44, in _setup
self._wrapped = Settings(settings_module)
File "/home/joel/.local/lib/python3.6/site-packages/django/conf/__init__.py", line 107, in __init__
mod = importlib.import_module(self.SETTINGS_MODULE)
File "/usr/lib/python3.6/importlib/__init__.py", line 126, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 994, in _gcd_import
File "<frozen importlib._bootstrap>", line 971, in _find_and_load
File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 678, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "/home/joel/myappointments/myappointments/settings.py", line 258, in <module>
Brander()
File "/home/joel/myappointments/myappointments/settings.py", line 16, in Brander
version = config['PROJECT']['version']
File "/usr/lib/python3.6/configparser.py", line 959, in __getitem__
raise KeyError(key)
KeyError: 'PROJECT'
我无法理解为什么仅在Django中启动代码时会发生此错误。
答案 0 :(得分:1)
您可以使用Django Constance来定义设置。例如:
CONSTANCE_CONFIG = {
'VERSION': ('0.0.1', 'Version'),
}
然后将'constance.context_processors.config'
添加到上下文处理器中,例如上述的documentation。然后在模板中使用它:
{{ config.VERSION }}