Django:如何将个人设置传递给manage.py

raa*_*cer 9 python django logging django-manage.py django-settings

我正在寻找一种方法来从命令行覆盖/定义一些单独的django设置,而无需额外的设置文件.

我现在需要的是每次运行管理命令时设置DEBUG设置或日志记录级别.但能够设置任何东西都会很棒.

raa*_*cer 6

这是我的解决方案.将以下代码添加到设置文件的底部.

# Process --set command line option
import sys
# This module can be imported several times,
# check if the option has been retrieved already.
if not hasattr(sys, 'arg_set'):
    # Search for the option.
    args = filter(lambda arg: arg[:6] == '--set=', sys.argv[1:])
    if len(args) > 0:
        expr = args[0][6:]
        # Remove the option from argument list, because the actual command
        # knows nothing about it.
        sys.argv.remove(args[0])
    else:
        # --set is not provided.
        expr = ''
    # Save option value for future use.
    sys.arg_set = expr
# Execute the option value.
exec sys.arg_set
Run Code Online (Sandbox Code Playgroud)

然后只需将任何代码传递给任何管理命令:

./manage.py runserver --set="DEBUG=True ; TEMPLATE_DEBUG=True"
Run Code Online (Sandbox Code Playgroud)