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

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


当前回答

运行一个开发SMTP服务器,它只输出发送给它的任何内容(如果您不想在开发服务器上实际安装SMTP)。

命令行:

python -m smtpd -n -c DebuggingServer localhost:1025

其他回答

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

当你开始设计你的网站时,网页设计应用程序是非常有用的。一旦导入,你可以添加它来生成示例文本:

{% load webdesign %}
{% lorem 5 p %}

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

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

使用IPython可以在任何级别跳转到代码中,并使用IPython的功能进行调试。一旦你安装了IPython,就把这段代码放在你想调试的地方:

from IPython.Shell import IPShellEmbed; IPShellEmbed()()

然后,刷新页面,转到runserver窗口,您将进入一个交互式IPython窗口。

我有一个片段设置在TextMate,所以我只是键入ipshell和点击标签。没有它我活不下去。

我从sorl-thumbnails应用程序的文档中学到了这一点。你可以在模板标签中使用“as”关键字来在模板的其他地方使用调用的结果。

例如:

{% url image-processor uid as img_src %}
<img src="{% thumbnail img_src 100x100 %}"/>

这一点在Django templatetag文档中提到过,但仅用于引用循环。他们并没有说你也可以在其他地方使用它(任何地方?)