灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
当前回答
有点晚了。但是Django Canvas最近出来了,它值得在这里占有一席之地。
不要用django-admin.py startproject启动你的项目。相反,你可以使用像Django Canvas这样的工具,用你需要的模块来拼凑一个空白项目。
你去那个网站,勾选一些选项,然后下载一个空白项目,很简单。
它具有所有常见的东西,如南模式迁移和命令扩展,以及这里提到的许多其他最佳实践。另外,它有一个很棒的start.sh/shart.bat脚本,可以安装python, virtualenv, pip, django和任何你需要从windows, osx或linux的新拷贝开始的东西。
其他回答
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}
)
通过django模板而不是as_(ul|table|p)()渲染表单。
本文展示了如何使用模板来呈现CusstomForms,而不是as_p(), as_table()…
要让它发挥作用,就要改变
从django import newforms as forms到From django import forms from django.newforms.forms import BoundField到from django.forms.forms import BoundField
如果您对模型进行更改
./manage.py dumpdata appname > appname_data.json
./manage.py reset appname
django-admin.py loaddata appname_data.json
当你开始设计你的网站时,网页设计应用程序是非常有用的。一旦导入,你可以添加它来生成示例文本:
{% load webdesign %}
{% lorem 5 p %}
在我的站点模板中,我使用了一组自定义标记。寻找一种自动加载的方法(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”)。