灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
当前回答
django.db.models。Get_model允许您在不导入模型的情况下检索模型。
James向我们展示了它有多方便:“Django提示:编写更好的模板标记-迭代4”。
其他回答
不要硬编码你的url !
使用url名称,使用反向函数来获取url本身。
在定义URL映射时,为URL指定名称。
urlpatterns += ('project.application.views'
url( r'^something/$', 'view_function', name="url-name" ),
....
)
确保每个URL的名称是唯一的。
我通常有一个一致的格式“项目-应用程序-视图”,例如:“cbx-forum-thread”用于线程视图。
更新(无耻地窃取ayaz的添加):
这个名称可以在带有url标记的模板中使用。
刚刚找到这个链接:http://lincolnloop.com/django-best-practices/#table-of-contents -“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}
)
不要在本地主机上运行Django开发服务器,而是在一个合适的网络接口上运行。例如:
python manage.py runserver 192.168.1.110:8000
or
python manage.py runserver 0.0.0.0:8000
然后,您不仅可以轻松地使用Fiddler (http://www.fiddler2.com/fiddler2/)或其他工具,如HTTP调试器(http://www.httpdebugger.com/)来检查您的HTTP头,而且还可以从LAN上的其他机器访问您的开发站点进行测试。
确保你有防火墙保护,尽管开发服务器是最小的,而且相对安全。
来自https://github.com/django-extensions/django-extensions的Django_extensions非常棒。
一些漂亮的。/manage.py命令:
shell_plus -自动导入所有INSTALLED_APPS中的模型 Show_urls -打印项目中所有应用程序中定义的所有url runscript -在项目环境中运行任何脚本(你可以使用模型和其他django相关模块)