灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
当前回答
使用djangorecipe管理你的项目
如果你正在编写一个新的应用程序,这个方法可以让你在项目之外非常容易地测试它 它允许你管理项目的依赖关系(例如,它应该依赖于哪个版本的应用程序)
你要做的就是这样开始:
Create a folder for your new website (or library) Create a buildout.cfg with following content in it: [buildout] parts=django [django] recipe=djangorecipe version=1.1.1 project=my_new_site settings=development Grab a bootstrap.py to get a local installation of buildout and place it within your directory. You can either go with the official one (sorry, Markdown didn't like part of the full link :-/ ) or with one that uses distribute instead of setuptools as described by Reinout van Rees. python bootstrap.py (or python bootstrap_dev.py if you want to use distribute). ./bin/buildout
就是这样。现在你应该有一个新的文件夹“my_new_site”,这是你新的django 1.1.1项目,在。/bin中你会找到django-script,它取代了正常安装的manage.py。
有什么好处?假设你想在你的项目中使用django-comment-spamfighter之类的东西。你所要做的就是把build - out.cfg修改成这样:
[buildout]
parts=django
[django]
recipe=djangorecipe
version=1.1.1
project=my_new_site
settings=development
eggs=
django-comments-spamfighter==0.4
请注意,我所做的只是添加了最后两行,表示django部分在0.4版中也应该有django-comments-spamfighter包。下次运行。/bin/buildout时,buildout将下载该包并修改。bin/django,将其添加到其PYTHONPATH中。
Djangorecipe也适用于用mod_wsgi部署你的项目。只需将wsgi=true设置添加到build - out.cfg中的django-part和“django. cfg”。Wsgi "将出现在你的。/bin文件夹中:-)
如果您将测试选项设置为应用程序列表,djangorecipe将为您创建一个漂亮的包装器,为项目中列出的应用程序运行所有测试。
如果你想在一个独立的环境中开发一个单独的应用程序进行调试等,Jakob Kaplan-Moss在他的博客上有一个相当完整的教程
其他回答
使用数据库迁移。使用南。
这增加了上面关于Django URL名称和反向URL调度的回复。
URL名称也可以在模板中有效地使用。例如,对于一个给定的URL模式:
url(r'(?P<project_id>\d+)/team/$', 'project_team', name='project_team')
你可以在模板中有以下内容:
<a href="{% url project_team project.id %}">Team</a>
使用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(例如重定向)将使装饰器短路,并像您期望的那样工作。
来自https://github.com/django-extensions/django-extensions的Django_extensions非常棒。
一些漂亮的。/manage.py命令:
shell_plus -自动导入所有INSTALLED_APPS中的模型 Show_urls -打印项目中所有应用程序中定义的所有url runscript -在项目环境中运行任何脚本(你可以使用模型和其他django相关模块)
如果你还没读过《Unbreaking Django》。它包含了很多关于django陷阱的有用信息。