django補充和form組件
Model常用操作:
- 參數:filter
- all,values,values_list
[obj(id,name,pwd,email),obj(id,name,pwd,email),]
models.UserInfo.objects.all()
[obj(id,name,email)] # pwd未取值
data_list = models.UserInfo.objects.all().only(‘name‘,‘email‘)
for item in data_list:
item.id
item.name
[obj(id,pwd)] # pwd未取值
data_list = models.UserInfo.objects.all().defer(‘name‘,‘email‘)
for item in data_list:
item.id
item.pwd
路由系統:
反向生成URL:
/index/ func name=a1
{% url "a1"}
reverse(‘x‘)
/index/(\d+)/ func name=a2
{% url "a2" 11 %}
reverse(‘x‘,args=(11,))
/index/(?P<nid>\d+)/ func name=a3
{% url "a2" nid=11 %}
reverse(‘x‘,kwargs={‘nid‘:11})
Django生命周期:
- wsgi
- wsgiref
- uwsgi
Http請求本質:
a1=123&a2=456
{a1:13}
今日概要:
1. 數據庫設計
- 屬性相同歸類到一張表中
- 連表有性能消耗
- 連表設計:
class UserType(models.Model):
"""
用戶類型表,個數經常變動
"""
title = models.CharField(max_length=32)
class UserInfo(models.Model):
"""
用戶表:講師和班主任
"""
username = models.CharField(max_length=32)
password = models.CharField(max_length=64)
email = models.CharField(max_length=32)
ut = models.ForeignKey(to="UserType")
- choices
# class UserInfo(models.Model):
# """
# 用戶表
# """
# username = models.CharField(max_length=32)
# password = models.CharField(max_length=64)
# email = models.CharField(max_length=32)
#
# user_type_choices = (
# (1, ‘班主任‘),
# (2, ‘講師‘),
# )
#
# user_type_id = models.IntegerField(choices=user_type_choices)
- 一張表中對同一個其他表做FK,M2M時,主要 related_name
- 註釋
- 補充:
"""
ID Title
1 圖片
2 挨踢1024
3 段子
"""
class NewsType(models.Model):
title = models.CharField(max_length=32)
"""
ID Title Summary News_Type
1 t.... 科技... 2
2 t.... 科技... 1
3 t.... 科技... 2
"""
class News(models.Model):
title = models.CharField(max_length=32)
summary = models.CharField(max_length=255)
news_type = models.ForeignKey(to="NewsType")
# 查看所有新聞
new_list = News.objects.all()
for row in new_list:
print(row.title,row.summary,row.news_type.title)
"""
ID Title Summary News_Type
1 t.... 科技... 2
2 t.... 科技... 1
3 t.... 科技... 2
"""
class News(models.Model):
title = models.CharField(max_length=32)
summary = models.CharField(max_length=255)
news_type_chices = (
(1,‘圖片‘),
(2,‘挨踢1024‘),
(3,‘段子‘),
)
news_type = models.IntegerField(choices=news_type_chices)
# 查看所有新聞
new_list = News.objects.all()
for row in new_list:
print(row.title,row.summary, row.get_news_type_display() )
2. 登錄
- 裝飾器
- Django內置+自定義配置文件
3. 老師管理
- Form組件
- 創建類,繼承Form
- 創建字段,字段=正則表達式; PS: 字段名稱,required, error_messages = {required,invalid}
- form = MyForm(data=request.POST)
- form.is_valid()
- form.cleaned_data
- form.errors
Form組件
1. 用戶請求數據驗證
2. 自動生成錯誤信息
3. 打包用戶提交正確信息
4. 錯誤:保留上次輸入內容
5. 定制頁面上顯示的HTML標簽
Django Form組件
1. 創建規則(類,字段)
class Foo:
username = xxx
password = xxx
email = xxx
2. 數據和規則進行匹配
form = Foo(data=xxx,initial=初始化)
form.is_valid()
form.cleaned_data
form.errors
class TeacherForm(Form): username = fields.CharField( required=True, error_messages={‘required‘:‘用戶名不能為空‘}, widget=widgets.TextInput(attrs={‘placeholder‘:‘用戶名‘,‘class‘:‘form-control‘}) ) # 不能為空 password = fields.CharField(required=True,error_messages={‘required‘:‘密碼不能為空‘}, widget=widgets.TextInput(attrs={‘placeholder‘:‘密碼‘,‘class‘:‘form-control‘})) # 不能為空 email = fields.EmailField(required=True,error_messages={‘required‘:‘郵箱不能為空‘,‘invalid‘:‘郵箱格式錯誤‘},widget=widgets.EmailInput(attrs={‘placeholder‘:‘郵箱‘,‘class‘:‘form-control‘})) # 不能為空,且郵箱格式 @auth def add_teacher(request): if request.method == ‘GET‘: form = TeacherForm() return render(request,‘add_teacher.html‘,{‘form‘:form}) else: """ 1. 用戶請求數據驗證 2. 自動生成錯誤信息 3. 打包用戶提交正確信息 4. 錯誤:保留上次輸入內容 5. 定制頁面上顯示的HTML標簽 Django Form組件 1. 創建規則(類,字段) class Foo: username = xxx password = xxx email = xxx 2. 數據和規則進行匹配 """ form = TeacherForm(data=request.POST) # 數據和規則放置一起 if form.is_valid(): # 開始校驗,並獲取校驗結果 # print(‘執行成功‘,form.cleaned_data) # 所有匹配成功,字典 # {‘username‘: ‘asd‘, ‘password‘: ‘sdf‘, ‘email‘: ‘[email protected]‘,‘ut_id‘:1} form.cleaned_data[‘ut_id‘] = 1 models.UserInfo.objects.create(**form.cleaned_data) return redirect(‘/teachers/‘) return render(request, ‘add_teacher.html‘,{‘form‘:form}) @auth def edit_teacher(request,nid): obj = models.UserInfo.objects.filter(id=nid,ut_id=1).first() if not obj: return redirect(‘/teachers/‘) if request.method == "GET": # 顯示input,並且將數據庫中的默認值填寫到input框中 form = TeacherForm(initial={‘username‘:obj.username,‘password‘:obj.password,‘email‘:obj.email}) return render(request,‘edit_teacher.html‘,{‘form‘:form}) else: form = TeacherForm(data=request.POST) if form.is_valid(): # 校驗成功 models.UserInfo.objects.filter(id=nid).update(**form.cleaned_data) return redirect(‘/teachers/‘) return render(request,‘edit_teacher.html‘,{‘form‘:form}) class TestForm(Form): caption = fields.CharField() # xxx = fields.ChoiceField(choices=[(1,‘講師‘),(2,‘班主任‘)]) # xxx = fields.ChoiceField(choices=models.UserInfo.objects.values_list(‘id‘,‘username‘)) # xxx = fields.ChoiceField(choices=models.UserType.objects.values_list(‘id‘,‘title‘)) xxx = fields.MultipleChoiceField(choices=models.UserInfo.objects.values_list(‘id‘,‘username‘)) def test(request): form = TestForm(initial={‘xxx‘:4}) form = TestForm(initial={‘xxx‘:[1,2,3]}) return render(request,‘test.html‘,{‘form‘:form})試用
django補充和form組件