灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
当前回答
运行一个开发SMTP服务器,它只输出发送给它的任何内容(如果您不想在开发服务器上实际安装SMTP)。
命令行:
python -m smtpd -n -c DebuggingServer localhost:1025
其他回答
在自定义视图装饰器中使用wraps装饰器来保留视图的名称、模块和文档字符串。如。
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.3, 2.4 fallback.
def view_decorator(fun):
@wraps(fun)
def wrapper():
# here goes your decorator's code
return wrapper
注意:如果作者没有定义__name__属性,则在基于类的视图(具有__call__方法定义的视图)上无效。作为一种变通方法:
from django.utils.decorators import available_attrs
...
@wraps(fun, assigned=available_attrs(fun))
使用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在他的博客上有一个相当完整的教程
当将变量从视图传递到模板时,输入响应字典会变得很乏味。我发现使用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的人来说还是很有帮助的。)
编辑:显然,显式比隐式更好,但这种方法在开发过程中是有帮助的。
PyCharm IDE是一个很好的编码环境,尤其是调试环境,内置了对Django的支持。
在视图代码中添加assert False以转储调试信息。