简体   繁体   English

在 Django 中访问 BASE_DIR 的推荐方式

[英]Recommended way of accessing BASE_DIR in Django

I am coding an automated menu module in Django that will list all the packages in BASE_DIR that have a urls.py file.我正在 Django 中编写一个自动菜单模块,它将列出 BASE_DIR 中具有 urls.py 文件的所有包。 For this I obviously need to access BASE_DIR, but I haven't been able to find a standard way of doing this.为此,我显然需要访问 BASE_DIR,但我一直无法找到执行此操作的标准方法。 I could just do:我只能这样做:

from myproject import settings

do_stuff(settings.BASE_DIR)

but I'd rather not hardcode it to myproject since this menu module could also be used for other applications.但我不想将它硬编码到 myproject 因为这个菜单模块也可以用于其他应用程序。 Is there a better solution?有更好的解决方案吗?

This isn't a question about BASE_DIR, but about importing settings.这不是关于 BASE_DIR 的问题,而是关于导入设置的问题。 Your proposed solution is not valid Python in any case: imports don't use file paths like that.您提出的解决方案在任何情况下都不是有效的 Python:导入不使用这样的文件路径。

The standard and fully documented way of importing settings in Django is this:在 Django 中导入设置的标准和完整记录的方法是这样的:

from django.conf import settings

This will always work, in any Django project, and will allow you to access any of the settings.这将始终适用于任何 Django 项目,并允许您访问任何设置。

For example, in a views.py file, we can do the following to use the value of BASE_DIR例如,在一个 views.py 文件中,我们可以执行以下操作来使用 BASE_DIR 的值

from django.conf import settings
value = settings.BASE_DIR

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

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