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

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


当前回答

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

其他回答

每个人都知道有一个可以使用“manage.py runserver”运行的开发服务器,但是你知道还有一个用于提供静态文件(CSS / JS / IMG)的开发视图吗?

新手总是感到困惑,因为Django没有提供任何提供静态文件的方法。这是因为开发团队认为这是实际Web服务器的工作。

但是在开发时,你可能不想设置Apache + mod_wisi,它很重。然后你只需要在urls.py中添加以下内容:

(r'^site_media/(?P<path>.*)$', 'django.views.static.serve',
        {'document_root': '/path/to/media'}),

您的CSS / JS / IMG将在www.yoursite.com/site_media/上提供。

当然,不要在生产环境中使用它。

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

在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》中得到了这个提示。

Django调试工具栏真的很棒。它实际上并不是一个工具栏,而是一个侧栏,告诉您是什么带来了您正在查看的页面的各种信息——DB查询、发送到模板的上下文变量、信号等等。

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

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}
    )