灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
当前回答
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 dumpdata appname > appname_data.json
./manage.py reset appname
django-admin.py loaddata appname_data.json
使用django调试工具栏。例如,它允许查看在呈现视图时执行的所有SQL查询,您还可以查看其中任何一个的堆栈跟踪。
使用信号动态地添加访问方法。
我在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的源代码。用于实际使用的模型。
为具有相同结构的遗留表集创建动态模型:
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()
这假设您拥有具有相同结构的遗留表。您不需要创建一个模型来包装每个表,而是定义一个基本模型,并动态构造与特定表交互所需的类。
在init上更改Django表单字段属性
有时向Form类传递额外的参数是有用的。
from django import forms
from mymodels import Group
class MyForm(forms.Form):
group=forms.ModelChoiceField(queryset=None)
email=forms.EmailField()
some_choices=forms.ChoiceField()
def __init__(self,my_var,*args,**kwrds):
super(MyForm,self).__init__(*args,**kwrds)
self.fields['group'].queryset=Group.objects.filter(...)
self.fields['email'].widget.attrs['size']='50'
self.fields['some_choices']=[[x,x] for x in list_of_stuff]
来源:Dzone片段