Py&djangoノート
3013 ワード
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()
の最初のパラメータは、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__