灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的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))
其他回答
刚刚找到这个链接:http://lincolnloop.com/django-best-practices/#table-of-contents -“Django最佳实践”。
Django没有应用程序设置,所以我做了我自己的app_settings.py检测。 在settings.py的底部,我添加了下面的代码:
import sys, os
# Append application settings without triggering the __init__.
for installed_app in INSTALLED_APPS:
# Ignore django applications
if not installed_app.startswith('django.'):
# Find the app (and the settings file)
for path in sys.path:
path = os.path.join(path, installed_app, 'app_settings.py')
if os.path.isfile(path):
# Application settings found
exec open(path).read()
它在所有的INSTALLED_APPS中检测app_settings.py。它将读取app_settings文件的内容并内联执行它,而不是导入它。如果直接导入app_settings,将会引发所有的Django导入错误(因为Django还没有初始化)。
所以我的app/app_settings.py看起来是这样的:
MIDDLEWARE_CLASSES += (
'app.middleware.FancyMiddleware',
)
现在应用程序只需要添加到INSTALLED_APPS,而不是找到所有的应用程序设置,并将它们添加到settings.py(中间件,url…)
注意:如果Django有一个钩子来附加额外的设置会更好,这样应用程序设置就可以在启动时(或运行时)添加。
我喜欢使用Python调试器pdb来调试Django项目。
这是一个学习如何使用它的有用链接:http://www.ferg.org/papers/debugging_in_python.html
安装Django命令扩展和pygraphviz,然后执行以下命令,得到一个非常漂亮的Django模型可视化:
./manage.py graph_models -a -g -o my_project.png
有点晚了。但是Django Canvas最近出来了,它值得在这里占有一席之地。
不要用django-admin.py startproject启动你的项目。相反,你可以使用像Django Canvas这样的工具,用你需要的模块来拼凑一个空白项目。
你去那个网站,勾选一些选项,然后下载一个空白项目,很简单。
它具有所有常见的东西,如南模式迁移和命令扩展,以及这里提到的许多其他最佳实践。另外,它有一个很棒的start.sh/shart.bat脚本,可以安装python, virtualenv, pip, django和任何你需要从windows, osx或linux的新拷贝开始的东西。