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

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


当前回答

当将变量从视图传递到模板时,输入响应字典会变得很乏味。我发现使用locals()一次性传递所有局部变量很好。

def show_thing(request, thing_id):
    thing = Thing.objects.get(pk=thing_id)
    return render_to_response('templates/things/show.html', locals())

(本质上不是一个隐藏的特性,但对于刚接触Python和Django的人来说还是很有帮助的。)

编辑:显然,显式比隐式更好,但这种方法在开发过程中是有帮助的。

其他回答

使用django调试工具栏。例如,它允许查看在呈现视图时执行的所有SQL查询,您还可以查看其中任何一个的堆栈跟踪。

这是一种非常简单的方法,永远不必在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}
    )

我喜欢使用Python调试器pdb来调试Django项目。

这是一个学习如何使用它的有用链接:http://www.ferg.org/papers/debugging_in_python.html

当我开始的时候,我不知道有一个Paginator,确保你知道它的存在!!