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

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


当前回答

来自https://github.com/django-extensions/django-extensions的Django_extensions非常棒。

一些漂亮的。/manage.py命令:

shell_plus -自动导入所有INSTALLED_APPS中的模型 Show_urls -打印项目中所有应用程序中定义的所有url runscript -在项目环境中运行任何脚本(你可以使用模型和其他django相关模块)

其他回答

dir()和提高评估误差()

为了在开发过程中调试/探索事物的状态,我使用了以下技巧:

...
  to_see = dir(inspect_this_thing)
  to_see2 = inspect_this_thing.some_attribute
  raise ValueError("Debugging")
...

当你处理django中没有很好文档的部分时,这是特别有用的。changed_fields是我最近使用的一个)。

当地人()。

使用python内置的locals()命令为你创建一个字典,而不是为模板上下文写出每个变量:

#This is tedious and not very DRY
return render_to_response('template.html', {"var1": var1, "var2":var2}, context_instance=RequestContext(request))

#95% of the time this works perfectly
return render_to_response('template.html', locals(), context_instance=RequestContext(request))

#The other 4.99%
render_dict = locals()
render_dict['also_needs'] = "this value"
return render_to_response('template.html', render_dict, context_instance=RequestContext(request))

在我的站点模板中,我使用了一组自定义标记。寻找一种自动加载的方法(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.db.models。Get_model允许您在不导入模型的情况下检索模型。

James向我们展示了它有多方便:“Django提示:编写更好的模板标记-迭代4”。

PyCharm IDE是一个很好的编码环境,尤其是调试环境,内置了对Django的支持。

使用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(例如重定向)将使装饰器短路,并像您期望的那样工作。