灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
当前回答
我没有足够的声誉来回复这个问题,但重要的是要注意,如果你打算使用Jinja,它不支持模板块名称中的'-'字符,而Django支持。这给我带来了很多问题,并浪费了很多时间试图追踪它生成的非常模糊的错误消息。
其他回答
Django没有应用程序设置,所以我做了我自己的app_settings.py检测。 在settings.py的底部,我添加了下面的代码:
import sys, os
# Append application settings without triggering the __init__.
for installed_app in INSTALLED_APPS:
# Ignore django applications
if not installed_app.startswith('django.'):
# Find the app (and the settings file)
for path in sys.path:
path = os.path.join(path, installed_app, 'app_settings.py')
if os.path.isfile(path):
# Application settings found
exec open(path).read()
它在所有的INSTALLED_APPS中检测app_settings.py。它将读取app_settings文件的内容并内联执行它,而不是导入它。如果直接导入app_settings,将会引发所有的Django导入错误(因为Django还没有初始化)。
所以我的app/app_settings.py看起来是这样的:
MIDDLEWARE_CLASSES += (
'app.middleware.FancyMiddleware',
)
现在应用程序只需要添加到INSTALLED_APPS,而不是找到所有的应用程序设置,并将它们添加到settings.py(中间件,url…)
注意:如果Django有一个钩子来附加额外的设置会更好,这样应用程序设置就可以在启动时(或运行时)添加。
每个人都知道有一个可以使用“manage.py runserver”运行的开发服务器,但是你知道还有一个用于提供静态文件(CSS / JS / IMG)的开发视图吗?
新手总是感到困惑,因为Django没有提供任何提供静态文件的方法。这是因为开发团队认为这是实际Web服务器的工作。
但是在开发时,你可能不想设置Apache + mod_wisi,它很重。然后你只需要在urls.py中添加以下内容:
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/path/to/media'}),
您的CSS / JS / IMG将在www.yoursite.com/site_media/上提供。
当然,不要在生产环境中使用它。
使用IPython可以在任何级别跳转到代码中,并使用IPython的功能进行调试。一旦你安装了IPython,就把这段代码放在你想调试的地方:
from IPython.Shell import IPShellEmbed; IPShellEmbed()()
然后,刷新页面,转到runserver窗口,您将进入一个交互式IPython窗口。
我有一个片段设置在TextMate,所以我只是键入ipshell和点击标签。没有它我活不下去。
django_extensions附带的。/manage.py runserver_plus工具真的很棒。
它创建了一个增强的调试页面,其中使用Werkzeug调试器为堆栈中的每个点创建交互式调试控制台(见截图)。它还提供了一个非常有用、方便的调试方法dump(),用于显示关于对象/帧的信息。
要安装,您可以使用pip:
pip install django_extensions
pip install Werkzeug
然后在settings.py中的INSTALLED_APPS元组中添加'django_extensions',并使用新的扩展启动开发服务器:
./manage.py runserver_plus
这将改变调试的方式。
Instead of using render_to_response to bind your context to a template and render it (which is what the Django docs usually show) use the generic view direct_to_template. It does the same thing that render_to_response does but it also automatically adds RequestContext to the template context, implicitly allowing context processors to be used. You can do this manually using render_to_response, but why bother? It's just another step to remember and another LOC. Besides making use of context processors, having RequestContext in your template allows you to do things like:
<a href="{{MEDIA_URL}}images/frog.jpg">A frog</a>
这是非常有用的。事实上,+1在一般的视图上。对于简单的应用程序,Django文档大多将它们作为快捷方式显示,甚至没有views.py文件,但你也可以在自己的视图函数中使用它们:
from django.views.generic import simple
def article_detail(request, slug=None):
article = get_object_or_404(Article, slug=slug)
return simple.direct_to_template(request,
template="articles/article_detail.html",
extra_context={'article': article}
)