问题描述
受问题系列...的隐藏功能"的启发,我很想知道您最喜欢的 Django 技巧或您知道的鲜为人知但有用的功能.
Inspired by the question series 'Hidden features of ...', I am curious to hear about your favorite Django tips or lesser known but useful features you know of.
- 请在每个答案中只包含一个提示.
- 如果有,请添加 Django 版本要求.
推荐答案
我只是从我自己的提示开始:)
I'm just going to start with a tip from myself :)
在 settings.py 中使用 os.path.dirname() 来避免硬编码的目录名.
如果您想在不同位置运行项目,请不要在 settings.py 中硬编码路径.如果您的模板和静态文件位于 Django 项目目录中,请在 settings.py 中使用以下代码:
Don't hardcode path's in your settings.py if you want to run your project in different locations. Use the following code in settings.py if your templates and static files are located within the Django project directory:
# settings.py
import os
PROJECT_DIR = os.path.dirname(__file__)
...
STATIC_DOC_ROOT = os.path.join(PROJECT_DIR, "static")
...
TEMPLATE_DIRS = (
os.path.join(PROJECT_DIR, "templates"),
)
致谢:我从截屏视频中得到了这个提示Django 从头开始'.
Credits: I got this tip from the screencast 'Django From the Ground Up'.
这篇关于最喜欢的 Django Tips &特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!