Modelform組件 Modelform就是model和from兩者結合起來的。它既有驗證,又有資料庫的操作 Modelform組件: Modelform註意事項: 1、類 示列(增刪改查): url: from django.conf.urls import url from django.co ...
Modelform組件
Modelform就是model和from兩者結合起來的。它既有驗證,又有資料庫的操作
Modelform組件:
Modelform: a. class Meta: model, # 對應Model的 fields=None, # 欄位 exclude=None, # 排除欄位 labels=None, # 提示信息 help_texts=None, # 幫助提示信息 widgets=None, # 自定義插件 error_messages=None, # 自定義錯誤信息(整體錯誤信息from django.core.exceptions import NON_FIELD_ERRORS) field_classes=None # 自定義欄位類 (也可以自定義欄位) localized_fields=('birth_date',) # 本地化,如:根據不同時區顯示數據 如: 資料庫中 2016-12-27 04:10:57 setting中的配置 TIME_ZONE = 'Asia/Shanghai' USE_TZ = True 則顯示: 2016-12-27 12:10:57 b. 驗證執行過程 is_valid -> full_clean -> 鉤子 -> 整體錯誤 c. 字典欄位驗證 def clean_欄位名(self): # 可以拋出異常 # from django.core.exceptions import ValidationError return "新值" d. 用於驗證 model_form_obj = XXOOModelForm() model_form_obj.is_valid() model_form_obj.errors.as_json() model_form_obj.clean() model_form_obj.cleaned_data e. 用於創建 model_form_obj = XXOOModelForm(request.POST) #### 頁面顯示,並提交 ##### # 預設保存多對多 obj = form.save(commit=True) # 不做任何操作,內部定義 save_m2m(用於保存多對多) obj = form.save(commit=False) obj.save() # 保存單表信息 obj.save_m2m() # 保存關聯多對多信息 f. 用於更新和初始化 obj = model.tb.objects.get(id=1) model_form_obj = XXOOModelForm(request.POST,instance=obj) ... PS: 單純初始化 model_form_obj = XXOOModelForm(initial={...})
Modelform註意事項:
1、類
class Foo(ModelFrom): class Meta:
model=models.Role
#fields="__all__" 所有的欄位 #fields=['caption',] 只取caption這個欄位
#xclude=['caption'] 除caption這個欄位外不取,剩餘的都取
error_massages={
'title':{'required':'名稱不能為空','invalid':'格式錯誤'}
}
widgets={
'title':wd.TextInput(attrs={'class':'c1'})
}
2.添加:
GET:
form=Foo()
POST:
form=Foo(instaance=obj,data=request.POST)
form.save()
示列(增刪改查):
url:
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^role/$', views.role), url(r'^role/add/$', views.role_add), url(r'^role/edit/(\d+)/$', views.role_edit), url(r'^usertype/$', views.user_type), url(r'^usertype/add/$', views.user_type_add), url(r'^usertype/edit/(\d+)/$', views.user_type_edit), #url(r'^role.html$', admin.site.urls), ]url
views:
from django.shortcuts import render,redirect,HttpResponse from app01 import models from django.forms import Form,ModelForm from django.forms import fields from django.forms import widgets as wd def role(request): roles = models.Role.objects.all() return render(request,'role.html',{'roles':roles}) class Role(ModelForm): class Meta: model = models.Role fields = "__all__" def role_add(request): if request.method == "GET": form = Role() return render(request,'role_add.html',{'form':form}) else: form = Role(request.POST) if form.is_valid(): form.save() # models.Role.objects.create(**form.cleaned_data) # models.Role.objects.create(**{'catpion':'123'}) return redirect('/role/') else: return render(request, 'role_add.html', {'form': form}) def role_edit(request,nid): obj = models.Role.objects.filter(id=nid).first() if not obj: return HttpResponse('數據不存在') if request.method == "GET": form = Role(instance=obj) return render(request,'role_edit.html',{'form':form}) else: form = Role(data=request.POST,instance=obj) if form.is_valid(): form.save() return redirect('/role/') else: return render(request, 'role_edit.html', {'form': form}) def user_type(request): user_type_list = models.UserType.objects.all() return render(request,'user_type.html',{'user_type_list':user_type_list}) class UserTypeModeForm(ModelForm): title = fields.CharField(max_length=6,required=True,widget=wd.Textarea()) class Meta: model = models.UserType fields = "__all__" error_messages = { 'title':{'required':'名稱不能為空','invalid':'格式錯誤'} } widgets = { 'title':wd.TextInput(attrs={'class':'c1'}) } # 鉤子函數 def user_type_add(request): if request.method == "GET": form = UserTypeModeForm() return render(request,'user_type_add.html',{'form':form}) else: form = UserTypeModeForm(request.POST) if form.is_valid(): form.save() return redirect('/usertype/') else: return render(request, 'user_type_add.html', {'form': form}) def user_type_edit(request,nid): obj = models.UserType.objects.filter(id=nid).first() if not obj: return HttpResponse('...') if request.method == 'GET': # 顯示預設值 form = UserTypeModeForm(instance=obj) return render(request,'user_type_edit.html',{'form':form}) else: form = UserTypeModeForm(instance=obj,data=request.POST) if form.is_valid(): form.save() return redirect('/usertype/') else: return render(request, 'user_type_edit.html', {'form': form})Views
role.html:
</head> <body> <ul> {% for row in roles %} <li>{{ row.caption }}</li> {% endfor %} </ul> </body> </html>role.html
role_add.html:
<body> <form method="post"> {% csrf_token %} <p>{{ form.caption }} {{ form.errors.caption.0 }}</p> <input type="submit" value="提交"> </form> </body>role_add
role_edit.html:
<body> <form method="post"> {% csrf_token %} <p>{{ form.caption }} {{ form.errors.caption.0 }}</p> <input type="submit" value="提交"> </form> </body>role_edit.html
user_type.html
<body> <ul> {% for row in user_type_list %} <li>{{ row.title }} - {{ row.roles.all }}</li> {% endfor %} </ul> </body>user_type.html
user_type_add.html
<body> <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="提交"> </form> </body>user_type_add.html
user_type_edit.html
<body> <form method="post" novalidate> {% csrf_token %} {{ form.as_p }} <input type="submit" value="提交"> </form> </body>user_type_edit.html