灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。

请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。


当前回答

Django调试工具栏真的很棒。它实际上并不是一个工具栏,而是一个侧栏,告诉您是什么带来了您正在查看的页面的各种信息——DB查询、发送到模板的上下文变量、信号等等。

其他回答

在生产环境中自动设置'DEBUG'属性(settings.py)

import socket

if socket.gethostname() == 'productionserver.com':
    DEBUG = False
else:
    DEBUG = True

由:http://nicksergeant.com/2008/automatically-setting-debug-in-your-django-app-based-on-server-hostname/

使用isapi-wsgi和Django -pyodbc在Windows上使用IIS和SQL Server运行Django !

这是一种非常简单的方法,永远不必在python shell中再次导入另一个模型。

首先,安装IPython(如果您不使用IPython,那么您有什么问题?)接下来,在django项目目录中创建一个python脚本ipythonrc.py,其中包含以下代码:

from django.db.models.loading import get_models 
for m in get_models(): 
     globals()[m.__name__] = m 
#NOTE: if you have two models with the same name you'll only end up with one of them

然后,在你的~/。ipython/ipythonrc文件,将以下代码放在“要加载和执行的Python文件”部分:

execfile /path/to/project/ipythonrc.py

现在,每次启动IPython或运行./manage.py shell时,您都将导入所有模型并准备使用。不需要再导入另一个模型。

您还可以将经常执行的任何其他代码放在ipythonrc.py文件中,以节省时间。

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}
    )

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有一个钩子来附加额外的设置会更好,这样应用程序设置就可以在启动时(或运行时)添加。