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

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


当前回答

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一起使用Jinja2。

如果你发现Django模板语言有极大的限制(就像我一样!),那么你不必被它所困。Django很灵活,模板语言与系统的其余部分是松散耦合的,所以只需插入另一种模板语言,并使用它来呈现http响应!

我使用的是Jinja2,它几乎就像一个增强版的django模板语言,它使用相同的语法,并允许你在if语句中使用表达式!不再制作自定义if标记,如if_item_in_list!你可以简单地说%{if item in list %},或者{% if object。字段< 10%}。

但这还不是全部;它有更多的功能来简化模板创建,我不能在这里一一介绍。

在视图代码中添加assert False以转储调试信息。

在urlconf中使用reverse。

这是我不明白为什么它不是默认的那些技巧之一。

这里有一个链接到我拿起它的地方: http://andr.in/2009/11/21/calling-reverse-in-django/

下面是代码片段:

从django.conf.urls.defaults导入* 从django.core.urlresolvers导入反向 从django.utils.functional导入lazy django。http导入HttpResponse Reverse_lazy = lazy(reverse, str) Urlpatterns = patterns(", url(r'^comehere/', lambda request: HttpResponse('Welcome!'), name='comehere'), url (r“^ $”,“django.views.generic.simple.redirect_to”, {'url': reverse_lazy('comehere')}, name='root') )

如果您对模型进行更改

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