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

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


当前回答

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

其他回答

我喜欢使用Python调试器pdb来调试Django项目。

这是一个学习如何使用它的有用链接:http://www.ferg.org/papers/debugging_in_python.html

因为Django的“视图”只需要是返回HttpResponse的可调用对象,你可以很容易地创建基于类的视图,就像Ruby on Rails和其他框架中的那样。

有几种方法可以创建基于类的视图,下面是我最喜欢的:

from django import http

class RestView(object):
    methods = ('GET', 'HEAD')

    @classmethod
    def dispatch(cls, request, *args, **kwargs):
        resource = cls()
        if request.method.lower() not in (method.lower() for method in resource.methods):
            return http.HttpResponseNotAllowed(resource.methods)
        try:
            method = getattr(resource, request.method.lower())
        except AttributeError:
            raise Exception("View method `%s` does not exist." % request.method.lower())
        if not callable(method):
            raise Exception("View method `%s` is not callable." % request.method.lower())
        return method(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        return http.HttpResponse()

    def head(self, request, *args, **kwargs):
        response = self.get(request, *args, **kwargs)
        response.content = ''
        return response

您可以在基本视图中添加各种其他东西,如条件请求处理和授权。

一旦你设置好了你的视图,你的urls.py将看起来像这样:

from django.conf.urls.defaults import *
from views import MyRestView

urlpatterns = patterns('',
    (r'^restview/', MyRestView.dispatch),
)

django_extensions附带的。/manage.py runserver_plus工具真的很棒。

它创建了一个增强的调试页面,其中使用Werkzeug调试器为堆栈中的每个点创建交互式调试控制台(见截图)。它还提供了一个非常有用、方便的调试方法dump(),用于显示关于对象/帧的信息。

要安装,您可以使用pip:

pip install django_extensions
pip install Werkzeug

然后在settings.py中的INSTALLED_APPS元组中添加'django_extensions',并使用新的扩展启动开发服务器:

./manage.py runserver_plus

这将改变调试的方式。

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

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

使用django-annoying的render_to装饰器而不是render_to_response。

@render_to('template.html')
def foo(request):
    bars = Bar.objects.all()
    if request.user.is_authenticated():
        return HttpResponseRedirect("/some/url/")
    else:
        return {'bars': bars}

# equals to
def foo(request):
    bars = Bar.objects.all()
    if request.user.is_authenticated():
        return HttpResponseRedirect("/some/url/")
    else:
        return render_to_response('template.html',
                              {'bars': bars},
                              context_instance=RequestContext(request))

编辑后指出,返回一个HttpResponse(例如重定向)将使装饰器短路,并像您期望的那样工作。