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

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

其他回答

安装Django命令扩展和pygraphviz,然后执行以下命令,得到一个非常漂亮的Django模型可视化:

./manage.py graph_models -a -g -o my_project.png

有点晚了。但是Django Canvas最近出来了,它值得在这里占有一席之地。

不要用django-admin.py startproject启动你的项目。相反,你可以使用像Django Canvas这样的工具,用你需要的模块来拼凑一个空白项目。

你去那个网站,勾选一些选项,然后下载一个空白项目,很简单。

它具有所有常见的东西,如南模式迁移和命令扩展,以及这里提到的许多其他最佳实践。另外,它有一个很棒的start.sh/shart.bat脚本,可以安装python, virtualenv, pip, django和任何你需要从windows, osx或linux的新拷贝开始的东西。

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

如果您对模型进行更改

./manage.py dumpdata appname > appname_data.json  
./manage.py reset appname
django-admin.py loaddata appname_data.json

从settings.py中删除数据库访问信息

我在Django站点的settings.py中做的一件事是从/etc文件中加载数据库访问信息。这样,每台机器的访问设置(数据库主机、端口、用户名、密码)都是不同的,并且像密码这样的敏感信息不在我的项目存储库中。您可能希望以类似的方式限制对工作者的访问,即让他们使用不同的用户名连接。

您还可以通过环境变量传递数据库连接信息,甚至只是一个配置文件的键或路径,并在settings.py中处理它。

例如,下面是我如何拉入我的数据库配置文件:

g = {}
dbSetup = {}
execfile(os.environ['DB_CONFIG'], g, dbSetup)
if 'databases' in dbSetup:
    DATABASES = dbSetup['databases']
else:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.mysql',
            # ...
        }
    }

不用说,你需要确保DB_CONFIG中的文件除了db管理员和Django本身外,其他用户都不能访问。默认情况下,Django应该参考开发人员自己的测试数据库。使用ast模块代替execfile可能还有更好的解决方案,但我还没有研究过。

我做的另一件事是为DB管理任务使用单独的用户。在我的manage.py中,我添加了以下序言:

# Find a database configuration, if there is one, and set it in the environment.
adminDBConfFile = '/etc/django/db_admin.py'
dbConfFile = '/etc/django/db_regular.py'
import sys
import os
def goodFile(path):
    return os.path.isfile(path) and os.access(path, os.R_OK)
if len(sys.argv) >= 2 and sys.argv[1] in ["syncdb", "dbshell", "migrate"] \
    and goodFile(adminDBConfFile):
    os.environ['DB_CONFIG'] = adminDBConfFile
elif goodFile(dbConfFile):
    os.environ['DB_CONFIG'] = dbConfFile

其中/etc/django/db_regular.py中的配置是针对只有SELECT, INSERT, UPDATE, DELETE权限的Django数据库用户,而/etc/django/db_admin.py中的配置是针对拥有CREATE, DROP, INDEX, ALTER, LOCK TABLES权限的用户。(迁移命令来自南方。)这在运行时为我提供了一些保护,防止Django代码弄乱我的模式,并限制了SQL注入攻击可能造成的损害(尽管您仍然应该检查和过滤所有用户输入)。

(摘自我对另一个问题的回答)