灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
当前回答
运行一个开发SMTP服务器,它只输出发送给它的任何内容(如果您不想在开发服务器上实际安装SMTP)。
命令行:
python -m smtpd -n -c DebuggingServer localhost:1025
其他回答
django-admin文档:
如果你使用Bash shell,可以考虑安装Django Bash完成脚本,它存在于Django发行版中的extras/django_bash_completion中。它支持django-admin.py和manage.py命令的制表符补全,所以你可以,例如…
django-admin.py类型。 按[TAB]查看所有可用选项。 输入sql,然后输入[TAB],查看所有名称以sql开头的可用选项。
使用“apps”文件夹来组织应用程序,而不需要编辑PYTHONPATH
当我想这样组织我的文件夹时,这个方法就很方便了:
apps/
foo/
bar/
site/
settings.py
urls.py
不用重写PYTHONPATH,也不用在每次导入时都添加应用程序,比如:
from apps.foo.model import *
from apps.bar.forms import *
在你的settings.py中添加
import os
import sys
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(PROJECT_ROOT, "apps"))
你已经准备好了:-)
我在http://codespatter.com/2009/04/10/how-to-add-locations-to-python-path-for-reusable-django-apps/上看到了这个
PyCharm和Wingware IDE是很好的工具,如果你有钱支付许可证。
因为我是一个很差的开发人员,所以我在Eclipse中使用PyDev。
Instead of using render_to_response to bind your context to a template and render it (which is what the Django docs usually show) use the generic view direct_to_template. It does the same thing that render_to_response does but it also automatically adds RequestContext to the template context, implicitly allowing context processors to be used. You can do this manually using render_to_response, but why bother? It's just another step to remember and another LOC. Besides making use of context processors, having RequestContext in your template allows you to do things like:
<a href="{{MEDIA_URL}}images/frog.jpg">A frog</a>
这是非常有用的。事实上,+1在一般的视图上。对于简单的应用程序,Django文档大多将它们作为快捷方式显示,甚至没有views.py文件,但你也可以在自己的视图函数中使用它们:
from django.views.generic import simple
def article_detail(request, slug=None):
article = get_object_or_404(Article, slug=slug)
return simple.direct_to_template(request,
template="articles/article_detail.html",
extra_context={'article': article}
)
每个人都知道有一个可以使用“manage.py runserver”运行的开发服务器,但是你知道还有一个用于提供静态文件(CSS / JS / IMG)的开发视图吗?
新手总是感到困惑,因为Django没有提供任何提供静态文件的方法。这是因为开发团队认为这是实际Web服务器的工作。
但是在开发时,你可能不想设置Apache + mod_wisi,它很重。然后你只需要在urls.py中添加以下内容:
(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': '/path/to/media'}),
您的CSS / JS / IMG将在www.yoursite.com/site_media/上提供。
当然,不要在生产环境中使用它。