灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
当前回答
当Django和另一个应用程序交换数据时,请求。Raw_post_data是一个好朋友。使用它来接收和自定义处理(比如XML数据)。
文档: http://docs.djangoproject.com/en/dev/ref/request-response/
其他回答
为具有相同结构的遗留表集创建动态模型:
class BaseStructure(models.Model):
name = models.CharField(max_length=100)
address = models.CharField(max_length=100)
class Meta:
abstract=True
class DynamicTable(models.Model):
table_name = models.CharField(max_length=20)
def get_model(self):
class Meta:
managed=False
table_name=self.table_name
attrs = {}
attrs['Meta'] = Meta
# type(new_class_name, (base,classes), {extra: attributes})
dynamic_class = type(self.table_name, (BaseStructure,), attrs)
return dynamic_class
customers = DynamicTable.objects.get(table_name='Customers').get_model()
me = customers.objects.get(name='Josh Smeaton')
me.address = 'Over the rainbow'
me.save()
这假设您拥有具有相同结构的遗留表。您不需要创建一个模型来包装每个表,而是定义一个基本模型,并动态构造与特定表交互所需的类。
Django没有应用程序设置,所以我做了我自己的app_settings.py检测。 在settings.py的底部,我添加了下面的代码:
import sys, os
# Append application settings without triggering the __init__.
for installed_app in INSTALLED_APPS:
# Ignore django applications
if not installed_app.startswith('django.'):
# Find the app (and the settings file)
for path in sys.path:
path = os.path.join(path, installed_app, 'app_settings.py')
if os.path.isfile(path):
# Application settings found
exec open(path).read()
它在所有的INSTALLED_APPS中检测app_settings.py。它将读取app_settings文件的内容并内联执行它,而不是导入它。如果直接导入app_settings,将会引发所有的Django导入错误(因为Django还没有初始化)。
所以我的app/app_settings.py看起来是这样的:
MIDDLEWARE_CLASSES += (
'app.middleware.FancyMiddleware',
)
现在应用程序只需要添加到INSTALLED_APPS,而不是找到所有的应用程序设置,并将它们添加到settings.py(中间件,url…)
注意:如果Django有一个钩子来附加额外的设置会更好,这样应用程序设置就可以在启动时(或运行时)添加。
使用信号动态地添加访问方法。
我在django photologue中看到过这种技术:对于添加的任何Size对象,post_init信号都会将相应的方法添加到Image模型中。 如果您添加了一个巨型站点,检索巨型分辨率图片的方法将是image.get_giant_url()。
这些方法是通过调用post_init信号中的add_accessor_methods来生成的:
def add_accessor_methods(self, *args, **kwargs):
for size in PhotoSizeCache().sizes.keys():
setattr(self, 'get_%s_size' % size,
curry(self._get_SIZE_size, size=size))
setattr(self, 'get_%s_photosize' % size,
curry(self._get_SIZE_photosize, size=size))
setattr(self, 'get_%s_url' % size,
curry(self._get_SIZE_url, size=size))
setattr(self, 'get_%s_filename' % size,
curry(self._get_SIZE_filename, size=size))
参见photologue的源代码。用于实际使用的模型。
这是一种非常简单的方法,永远不必在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模板而不是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