灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
当前回答
PyCharm IDE是一个很好的编码环境,尤其是调试环境,内置了对Django的支持。
其他回答
不要硬编码你的url !
使用url名称,使用反向函数来获取url本身。
在定义URL映射时,为URL指定名称。
urlpatterns += ('project.application.views'
url( r'^something/$', 'view_function', name="url-name" ),
....
)
确保每个URL的名称是唯一的。
我通常有一个一致的格式“项目-应用程序-视图”,例如:“cbx-forum-thread”用于线程视图。
更新(无耻地窃取ayaz的添加):
这个名称可以在带有url标记的模板中使用。
不要编写自己的登录页面。如果你使用django.contrib.auth。
真正的,肮脏的秘密是,如果你也在使用django.contrib。Admin和django.template.loaders.app_directories。Load_template_source在你的模板加载器中,你也可以免费获得你的模板!
# somewhere in urls.py
urlpatterns += patterns('django.contrib.auth',
(r'^accounts/login/$','views.login', {'template_name': 'admin/login.html'}),
(r'^accounts/logout/$','views.logout'),
)
当将变量从视图传递到模板时,输入响应字典会变得很乏味。我发现使用locals()一次性传递所有局部变量很好。
def show_thing(request, thing_id):
thing = Thing.objects.get(pk=thing_id)
return render_to_response('templates/things/show.html', locals())
(本质上不是一个隐藏的特性,但对于刚接触Python和Django的人来说还是很有帮助的。)
编辑:显然,显式比隐式更好,但这种方法在开发过程中是有帮助的。
在生产环境中自动设置'DEBUG'属性(settings.py)
import socket
if socket.gethostname() == 'productionserver.com':
DEBUG = False
else:
DEBUG = True
由:http://nicksergeant.com/2008/automatically-setting-debug-in-your-django-app-based-on-server-hostname/
通过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