標籤:ati .post type json include body 瀏覽器 href lex
路由系統:
1. /index/ -> def index(request)
2.
/detail-(\d+)/ -> def detail(request,nid)
/detail-(?P<nid>\d+)/ -> def detail(request,nid)
3.
/index/ -> def index(request) name=n1
使用別名產生URL:
範本語言: {% url n1 %} -> /index/
視圖函數:
reverse(name="n1") -> /index/
4.
/web/ include("app01.urls")
視圖函數:
1. 函數至少一個參數
2. request
request.method
request.GET
request.POST (要求標頭:Content-Type:application/x-www-form-urlencoded; charset=UTF-8)
request.body
request.FILES
...
3.
return HttpResponse(..)
return render()
return redirect()
模板引擎:
1. 基本文法
return renderI(request, ‘xxx.html‘, {‘v‘: [1,2,3,4],‘d‘:{‘k1‘:‘v1‘,‘k2‘:‘v2‘} })
xxx.html
{{v.2}}
{% for i in d %}
{{i}} --> key
{% endfor %}
{% for k,v in d.items %}
{{k}}--{{v}}
{% endfor %}
2. 函數
Django提供函數
simple_tag
filter
ORM操作:
1. 建立表
class UserInfo(models.Model):
# nid = models.AutoField(primary_key=True) int
# nid = models.BigAutoField(primary_key=True) long
name = models.CharField(max_length=32)
pwd = models.CharField(max_length=32)
2. 動作表
q = models.UserInfo.objects.all()
Queryset = [obj(id,name,pwd),obj(id,name,pwd),obj(id,name,pwd),]
q = models.UserInfo.objects.values(‘name‘,‘pwd‘)
Queryset = [{"name":‘alex‘,‘pwd‘:123},{"name":‘alex1‘,‘pwd‘:123sfd},{"name":‘alex1‘,‘pwd‘:123sfd},]
q = models.UserInfo.objects.values_list(‘name‘,‘pwd‘)
Queryset = [(‘alex‘,123),(‘alex‘,123),(‘alex‘,123),(‘alex‘,123),]
q = models.UserInfo.objects.filter(name=‘alex‘)
[obj,]
q = models.UserInfo.objects.get(name=‘alex‘)
q = models.UserInfo.objects.filter(name=‘alex‘).first()
...
今日內容:
1. FBV和CBV
FBV:
url(r‘^index/‘, views.index),
def index(request):
print(‘.....‘)
if request.method == ‘GET‘:
pass
elif request.method == ‘POST‘:
pass
return HttpResponse(‘....‘)
CBV:
url(r‘^user/‘, views.User.as_view()),
class User(View):
def dispatch(self, request, *args, **kwargs):
print(‘before‘)
obj = super(User,self).dispatch(request, *args, **kwargs)
print(‘after‘)
return obj
def get(self,request):
print("get...")
return HttpResponse(‘...‘)
def post(self,request):
print("post...")
return HttpResponse(‘...‘)
2. ORM操作
a. 建立表
一對多
多對多
- 建立第三表:
- 自己定義第三張表 :列無限制
- ManyToManyField欄位: 列限制(三)
- 無法直接,只能通過ManyToManyField欄位進行間接操作
b. 操作
正向
dp
反向
userinfo
userinfo_set
3. Cookie
在瀏覽器上儲存的簡直對
應用:
可做使用者登入
做投票
4. session
伺服器端儲存的簡直對
{
asdfasdfasdf: {‘user‘:‘asdf‘,‘pws‘:‘asdf‘}
}
5. Ajax操作
#
$.ajax({
url: ‘/aj/‘, # 提交地址
type: "POST", # 提交方式
data: {uuu: u, ppp:p}, # 提交資料
dataType: "JSON",
success:function (data) { # 回呼函數,登入成功後自動執行
# 將字典形式的字串,發序列化成為字典對象(json對象)
# var data_dict = JSON.parse(data);
if(data_dict.status){
location.href = "/home/"
}else{
alert(data_dict.error);
}
}
})
djange表操作和ajax