灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。

请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。


当前回答

PyCharm和Wingware IDE是很好的工具,如果你有钱支付许可证。

因为我是一个很差的开发人员,所以我在Eclipse中使用PyDev。

其他回答

dir()和提高评估误差()

为了在开发过程中调试/探索事物的状态,我使用了以下技巧:

...
  to_see = dir(inspect_this_thing)
  to_see2 = inspect_this_thing.some_attribute
  raise ValueError("Debugging")
...

当你处理django中没有很好文档的部分时,这是特别有用的。changed_fields是我最近使用的一个)。

当地人()。

使用python内置的locals()命令为你创建一个字典,而不是为模板上下文写出每个变量:

#This is tedious and not very DRY
return render_to_response('template.html', {"var1": var1, "var2":var2}, context_instance=RequestContext(request))

#95% of the time this works perfectly
return render_to_response('template.html', locals(), context_instance=RequestContext(request))

#The other 4.99%
render_dict = locals()
render_dict['also_needs'] = "this value"
return render_to_response('template.html', render_dict, context_instance=RequestContext(request))

与Django一起使用Jinja2。

如果你发现Django模板语言有极大的限制(就像我一样!),那么你不必被它所困。Django很灵活,模板语言与系统的其余部分是松散耦合的,所以只需插入另一种模板语言,并使用它来呈现http响应!

我使用的是Jinja2,它几乎就像一个增强版的django模板语言,它使用相同的语法,并允许你在if语句中使用表达式!不再制作自定义if标记,如if_item_in_list!你可以简单地说%{if item in list %},或者{% if object。字段< 10%}。

但这还不是全部;它有更多的功能来简化模板创建,我不能在这里一一介绍。

当你开始设计你的网站时,网页设计应用程序是非常有用的。一旦导入,你可以添加它来生成示例文本:

{% load webdesign %}
{% lorem 5 p %}

在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片段

使用isapi-wsgi和Django -pyodbc在Windows上使用IIS和SQL Server运行Django !