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

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


当前回答

这是一种非常简单的方法,永远不必在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文件中,以节省时间。

其他回答

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

使用数据库迁移。使用南。

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

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

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

我就从我自己的一个建议开始吧:)

在settings.py中使用os.path.dirname()来避免硬编码的dirname。

如果你想在不同的位置运行你的项目,不要在你的settings.py中硬编码路径。如果你的模板和静态文件位于Django项目目录中,在settings.py中使用下面的代码:

# settings.py
import os
PROJECT_DIR = os.path.dirname(__file__)
...
STATIC_DOC_ROOT = os.path.join(PROJECT_DIR, "static")
...
TEMPLATE_DIRS = (
    os.path.join(PROJECT_DIR, "templates"),
)

工作人员:我从视频《Django from the Ground Up》中得到了这个提示。

使用djangorecipe管理你的项目

如果你正在编写一个新的应用程序,这个方法可以让你在项目之外非常容易地测试它 它允许你管理项目的依赖关系(例如,它应该依赖于哪个版本的应用程序)

你要做的就是这样开始:

Create a folder for your new website (or library) Create a buildout.cfg with following content in it: [buildout] parts=django [django] recipe=djangorecipe version=1.1.1 project=my_new_site settings=development Grab a bootstrap.py to get a local installation of buildout and place it within your directory. You can either go with the official one (sorry, Markdown didn't like part of the full link :-/ ) or with one that uses distribute instead of setuptools as described by Reinout van Rees. python bootstrap.py (or python bootstrap_dev.py if you want to use distribute). ./bin/buildout

就是这样。现在你应该有一个新的文件夹“my_new_site”,这是你新的django 1.1.1项目,在。/bin中你会找到django-script,它取代了正常安装的manage.py。

有什么好处?假设你想在你的项目中使用django-comment-spamfighter之类的东西。你所要做的就是把build - out.cfg修改成这样:


[buildout]
parts=django

[django]
recipe=djangorecipe
version=1.1.1
project=my_new_site
settings=development
eggs=
    django-comments-spamfighter==0.4

请注意,我所做的只是添加了最后两行,表示django部分在0.4版中也应该有django-comments-spamfighter包。下次运行。/bin/buildout时,buildout将下载该包并修改。bin/django,将其添加到其PYTHONPATH中。

Djangorecipe也适用于用mod_wsgi部署你的项目。只需将wsgi=true设置添加到build - out.cfg中的django-part和“django. cfg”。Wsgi "将出现在你的。/bin文件夹中:-)

如果您将测试选项设置为应用程序列表,djangorecipe将为您创建一个漂亮的包装器,为项目中列出的应用程序运行所有测试。

如果你想在一个独立的环境中开发一个单独的应用程序进行调试等,Jakob Kaplan-Moss在他的博客上有一个相当完整的教程