灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
灵感来自问题系列的隐藏特征…,我很想听听你最喜欢的Django技巧或你知道的不太为人所知但有用的功能。
请在每个答案中只包含一个技巧。 添加Django版本要求(如果有的话)。
当前回答
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}
)
其他回答
在自定义视图装饰器中使用wraps装饰器来保留视图的名称、模块和文档字符串。如。
try:
from functools import wraps
except ImportError:
from django.utils.functional import wraps # Python 2.3, 2.4 fallback.
def view_decorator(fun):
@wraps(fun)
def wrapper():
# here goes your decorator's code
return wrapper
注意:如果作者没有定义__name__属性,则在基于类的视图(具有__call__方法定义的视图)上无效。作为一种变通方法:
from django.utils.decorators import available_attrs
...
@wraps(fun, assigned=available_attrs(fun))
我从sorl-thumbnails应用程序的文档中学到了这一点。你可以在模板标签中使用“as”关键字来在模板的其他地方使用调用的结果。
例如:
{% url image-processor uid as img_src %}
<img src="{% thumbnail img_src 100x100 %}"/>
这一点在Django templatetag文档中提到过,但仅用于引用循环。他们并没有说你也可以在其他地方使用它(任何地方?)
每个人都知道有一个可以使用“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/上提供。
当然,不要在生产环境中使用它。
因为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),
)
来自https://github.com/django-extensions/django-extensions的Django_extensions非常棒。
一些漂亮的。/manage.py命令:
shell_plus -自动导入所有INSTALLED_APPS中的模型 Show_urls -打印项目中所有应用程序中定义的所有url runscript -在项目环境中运行任何脚本(你可以使用模型和其他django相关模块)