灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
当前回答
当我开始的时候,我不知道有一个Paginator,确保你知道它的存在!!
其他回答
通过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
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))
这是一种非常简单的方法,永远不必在python shell中再次导入另一个模型。
首先,安装IPython(如果您不使用IPython,那么您有什么问题?)接下来,在django项目目录中创建一个python脚本ipythonrc.py,其中包含以下代码:
from django.db.models.loading import get_models
for m in get_models():
globals()[m.__name__] = m
#NOTE: if you have two models with the same name you'll only end up with one of them
然后,在你的~/。ipython/ipythonrc文件,将以下代码放在“要加载和执行的Python文件”部分:
execfile /path/to/project/ipythonrc.py
现在,每次启动IPython或运行./manage.py shell时,您都将导入所有模型并准备使用。不需要再导入另一个模型。
您还可以将经常执行的任何其他代码放在ipythonrc.py文件中,以节省时间。
使用django-annoying的render_to装饰器而不是render_to_response。
@render_to('template.html')
def foo(request):
bars = Bar.objects.all()
if request.user.is_authenticated():
return HttpResponseRedirect("/some/url/")
else:
return {'bars': bars}
# equals to
def foo(request):
bars = Bar.objects.all()
if request.user.is_authenticated():
return HttpResponseRedirect("/some/url/")
else:
return render_to_response('template.html',
{'bars': bars},
context_instance=RequestContext(request))
编辑后指出,返回一个HttpResponse(例如重定向)将使装饰器短路,并像您期望的那样工作。