最喜欢的Django技巧和功能?

308

受到“Hidden features of…”问题系列的启发,我很想听听您所知道的Django技巧或较少人知但实用的功能。

  • 每个答案请仅包含一个技巧。
  • 如果有要求,请注明Django版本。
55个回答

5

使用 djangorecipe 来管理您的项目

  • 如果您正在编写新应用程序,则此配方使在项目之外测试它变得非常容易
  • 它允许您管理项目的依赖项(例如,它应该依赖于某个应用程序的哪个版本)

您只需要执行以下操作即可开始:

  1. Create a folder for your new website (or library)
  2. 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
    
  3. 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.
  4. python bootstrap.py (or python bootstrap_dev.py if you want to use distribute).
  5. ./bin/buildout

就这样。现在你应该有一个名为“my_new_site”的新文件夹,它是你的新Django 1.1.1项目,在./bin中,你会找到django脚本,它替换了普通安装中的manage.py。

好处是什么?假设你想在项目中使用像django-comment-spamfighter这样的东西。你只需要更改你的buildout.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部署项目。只需在buildout.cfg的django部分添加wsgi=true设置,就会在您的./bin文件夹中出现一个"django.wsgi"文件 :-)
如果您将test选项设置为应用程序列表,则djangorecipe将为您创建一个漂亮的包装器,用于运行项目中列出的所有应用程序的测试。
如果您想要在独立环境中开发单个应用程序进行调试等操作,Jakob Kaplan-Moss在他的博客上有一个非常完整的教程。

5

在您的urlconf中使用reverse。

这是其中一种技巧,我不明白为什么它不是默认设置。

这里是我学到这个技巧的链接: http://andr.in/2009/11/21/calling-reverse-in-django/

以下是代码片段:

from django.conf.urls.defaults import *
from django.core.urlresolvers import reverse
from django.utils.functional import lazy
from django.http import HttpResponse

reverse_lazy = lazy(reverse, str)

urlpatterns = patterns('',
url(r'^comehere/', lambda request: HttpResponse('Welcome!'), name='comehere'),
url(r'^$', 'django.views.generic.simple.redirect_to',
{'url': reverse_lazy('comehere')}, name='root')
)

4
那是什么意思,我为什么要这么做呢? - Dominic Rodger
1
Reverse 就像 URL 标签一样,它“返回与给定视图函数和可选参数匹配的绝对 URL(即没有域名的 URL)”。我避免硬编码绝对 URL。当我部署到 Web 服务器时,应用程序可能不是根挂载点,因此在测试服务器上,像 /app/url/ 这样的 URL 可能有效,但在部署服务器上,它可能是 /mountpoint/app/url。Reverse 在 views.py 中起作用。但在 urls.py 中不起作用。它会出现错误:“包含的 urlconf foo.urls 中没有任何模式”。这个技巧可以让你避免需要在视图中包装 URLconf。 - jfenwick
2
-1,这是一个可怕的hack来解决根URL问题。PythonOption django.root是正确的方法。请参阅相关文档:http://docs.djangoproject.com/en/1.2/howto/deployment/modpython/#basic-configuration - Agos

5

4
这是一种非常简单的方法,可以让你在Python shell中永远不必再导入你的模型。
首先,安装IPython(如果你不使用IPython,那么你怎么了?)。接下来,在你的Django项目目录中创建一个名为ipythonrc.py的Python脚本,并将以下代码放入其中:
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 files to load and execute" 部分中放入以下代码:

execfile /path/to/project/ipythonrc.py

现在每次启动IPython或运行./manage.py shell时,您都可以已经导入并准备好使用所有模型。再也不需要导入其他模型了。您还可以将您经常执行的任何其他代码放入ipythonrc.py文件中,以节省时间。

7
考虑使用“Django命令扩展”,它会添加"./manage.py shell_plus"命令,为你完成此操作(还有其他很酷的功能)。 - Carl G

4

在初始化时更改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]

source: Dzone snippets


太棒了!我刚刚一直在将我的表单类包装在函数中,但这似乎不像 Python 风格。 - Spike

2

如果您有足够的资金支付许可证,那么PyCharm和Wingware IDE是非常好的工具。

由于我是一名贫穷的开发者,所以我使用PyDevEclipse


2

django_extensions来自https://github.com/django-extensions/django-extensions,非常实用。

以下是一些很棒的./manage.py命令:

  • shell_plus - 自动导入所有已安装应用程序的模型
  • show_urls - 显示项目中所有应用程序定义的URL
  • runscript - 在项目上下文中运行任何脚本(您可以使用模型和其他与Django相关的模块)

1

来晚了一点,但是Django Canvas最近推出了,它应该在这里占据一席之地。

不要使用django-admin.py startproject开始你的项目。相反,你可以使用类似Django Canvas的工具来帮助你组合一个空白项目和你需要的模块。

你只需前往该网站,勾选一些选项,然后下载一个空白项目,非常简单。

它拥有所有常见的东西,如South模式迁移和命令扩展,以及本文提到的许多其他最佳实践。此外,它还有一个很棒的start.sh/shart.bat脚本,可以安装Python、Virtualenv、Pip、Django以及你需要从Windows、OSX或Linux的新副本开始的任何内容。


1

如尚未阅读,建议查看Unbreaking Django,其中包含有关Django陷阱的大量有用信息。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接