灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加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))
不要编写自己的登录页面。如果你使用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'),
)
在生产环境中自动设置'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/
我从sorl-thumbnails应用程序的文档中学到了这一点。你可以在模板标签中使用“as”关键字来在模板的其他地方使用调用的结果。
例如:
{% url image-processor uid as img_src %}
<img src="{% thumbnail img_src 100x100 %}"/>
这一点在Django templatetag文档中提到过,但仅用于引用循环。他们并没有说你也可以在其他地方使用它(任何地方?)
通过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