灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
当前回答
每个人都知道有一个可以使用“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/上提供。
当然,不要在生产环境中使用它。
其他回答
当我开始的时候,我不知道有一个Paginator,确保你知道它的存在!!
Virtualenv + Python =救生圈,如果你在多个Django项目中工作,而且它们可能都不依赖于同一个版本的Django/应用程序。
在自定义视图装饰器中使用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))
使用“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/上看到了这个
使用xml_models创建使用XML REST API后端(而不是SQL后端)的Django模型。这是非常有用的,特别是在对第三方api建模时——你会得到你习惯的所有相同的QuerySet语法。您可以从PyPI安装它。
来自API的XML:
<profile id=4>
<email>joe@example.com</email>
<first_name>Joe</first_name>
<last_name>Example</last_name>
<date_of_birth>1975-05-15</date_of_birth>
</profile>
现在在python中:
class Profile(xml_models.Model):
user_id = xml_models.IntField(xpath='/profile/@id')
email = xml_models.CharField(xpath='/profile/email')
first = xml_models.CharField(xpath='/profile/first_name')
last = xml_models.CharField(xpath='/profile/last_name')
birthday = xml_models.DateField(xpath='/profile/date_of_birth')
finders = {
(user_id,): settings.API_URL +'/api/v1/profile/userid/%s',
(email,): settings.API_URL +'/api/v1/profile/email/%s',
}
profile = Profile.objects.get(user_id=4)
print profile.email
# would print 'joe@example.com'
它还可以处理关系和集合。我们每天都在大量使用的产品代码中使用它,所以即使它是测试版,它也是非常有用的。它还有一组很好的存根,可以在测试中使用。
(免责声明:虽然我不是这个库的作者,但我现在是一个提交者,已经进行了一些小的提交)