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

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


当前回答

在我的站点模板中,我使用了一组自定义标记。寻找一种自动加载的方法(DRY,记得吗?),我发现如下:

from django import template
template.add_to_builtins('project.app.templatetags.custom_tag_module')

如果你把它放在一个默认加载的模块中(例如你的主urlconf),你将有来自自定义标签模块的标签和过滤器在任何模板中可用,而不需要使用{% load custom_tag_module %}。

传递给template.add_to_builtins()的参数可以是任何模块路径;您的自定义标记模块不必存在于特定的应用程序中。例如,它也可以是项目根目录中的一个模块。“project.custom_tag_module”)。

其他回答

使用信号动态地添加访问方法。

我在django photologue中看到过这种技术:对于添加的任何Size对象,post_init信号都会将相应的方法添加到Image模型中。 如果您添加了一个巨型站点,检索巨型分辨率图片的方法将是image.get_giant_url()。

这些方法是通过调用post_init信号中的add_accessor_methods来生成的:

def add_accessor_methods(self, *args, **kwargs):
    for size in PhotoSizeCache().sizes.keys():
        setattr(self, 'get_%s_size' % size,
                curry(self._get_SIZE_size, size=size))
        setattr(self, 'get_%s_photosize' % size,
                curry(self._get_SIZE_photosize, size=size))
        setattr(self, 'get_%s_url' % size,
                curry(self._get_SIZE_url, size=size))
        setattr(self, 'get_%s_filename' % size,
                curry(self._get_SIZE_filename, size=size))

参见photologue的源代码。用于实际使用的模型。

使用异步任务。使用芹菜

使用数据库迁移。使用南。

这增加了上面关于Django URL名称和反向URL调度的回复。

URL名称也可以在模板中有效地使用。例如,对于一个给定的URL模式:

url(r'(?P<project_id>\d+)/team/$', 'project_team', name='project_team')

你可以在模板中有以下内容:

<a href="{% url project_team project.id %}">Team</a>

使用django-annoying的render_to装饰器而不是render_to_response。

@render_to('template.html')
def foo(request):
    bars = Bar.objects.all()
    if request.user.is_authenticated():
        return HttpResponseRedirect("/some/url/")
    else:
        return {'bars': bars}

# equals to
def foo(request):
    bars = Bar.objects.all()
    if request.user.is_authenticated():
        return HttpResponseRedirect("/some/url/")
    else:
        return render_to_response('template.html',
                              {'bars': bars},
                              context_instance=RequestContext(request))

编辑后指出,返回一个HttpResponse(例如重定向)将使装饰器短路,并像您期望的那样工作。