Start
如果py文件中有中文,文件首行必须加上# -*- coding: utf-8 -*-
Django:表格后面还有一个{% csrf_token %}的标签。csrf 全称是 Cross Site Request Forgery。这是Django提供的防止伪装提交请求的功能。POST 方法提交的表格,必须有此标签。
登录检验封装例子
封装登录状态检验
def requires_login(view):
def new_view(request, *args, **kwargs):
if not request.user.is_authenticated():
return HttpResponseRedirect('/accounts/login/')
return view(request, *args, **kwargs)
return new_view
在urls.py里调用
from django.conf.urls.defaults import *
from mysite.views import requires_login, my_view1, my_view2, my_view3
urlpatterns = patterns('',
(r'^view1/$', requires_login(my_view1)),
(r'^view2/$', requires_login(my_view2)),
(r'^view3/$', requires_login(my_view3)),
)
django模型查询
在对模型进行查询时
query_set = Models.objects.filter(Filter)
此时只是构建了query
语句,然而并没有进行实际的数据库操作,当进行
print query_set
这时候才进行实际的数据库操作。
django文档原文
QuerySets are lazy – the act of creating a QuerySet doesn’t involve any database activity. You can stack filters together all day long, and Django won’t actually run the query until the QuerySet is evaluated. Take a look at this example:
>>> q = Entry.objects.filter(headline__startswith="What")
>>> q = q.filter(pub_date__lte=datetime.date.today())
>>> q = q.exclude(body_text__icontains="food")
>>> print(q)
Though this looks like three database hits, in fact it hits the database only once, at the last line (print(q)). In general, the results of a QuerySet aren’t fetched from the database until you “ask” for them. When you do, the QuerySet is evaluatedby accessing the database. For more details on exactly when evaluation takes place, see When QuerySets are evaluated.
视图渲染
def get_absolute_url(self):
return reverse('blog:detail', kwargs={'pk':self.pk})
由上例子可见,reverse()
的第一个参数可以使的Django顺利找到blog
应用下name
为detail
的视图函数,于是reverse
会去解析这个视图对应的URL。reverse()
函数的第一个参数中的空格会被视为合理的符号,例如app_name:index
和app_name: index
中,会分别匹配到app_name
应用中的index
方法和index
方法,空格会被视为方法名中合理的组成部分。
动态生成URL例子
class Chain(object):
def __init__(self, path='GET '):
self._path = path
def __getattr__(self, path):
return Chain('%s/%s' % (self._path, path))
def __call__(self,path):
return Chain('%s/%s' % (self._path, path))
def __str__(self):
return self._path
__repr__ = __str__