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

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


当前回答

不要在本地主机上运行Django开发服务器,而是在一个合适的网络接口上运行。例如:

python manage.py runserver 192.168.1.110:8000

or

python manage.py runserver 0.0.0.0:8000

然后,您不仅可以轻松地使用Fiddler (http://www.fiddler2.com/fiddler2/)或其他工具,如HTTP调试器(http://www.httpdebugger.com/)来检查您的HTTP头,而且还可以从LAN上的其他机器访问您的开发站点进行测试。

确保你有防火墙保护,尽管开发服务器是最小的,而且相对安全。

其他回答

PyCharm IDE是一个很好的编码环境,尤其是调试环境,内置了对Django的支持。

如果你还没读过《Unbreaking Django》。它包含了很多关于django陷阱的有用信息。

通过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

使用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'

它还可以处理关系和集合。我们每天都在大量使用的产品代码中使用它,所以即使它是测试版,它也是非常有用的。它还有一组很好的存根,可以在测试中使用。

(免责声明:虽然我不是这个库的作者,但我现在是一个提交者,已经进行了一些小的提交)

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

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