Django之Modelform组件
2018-06-17 23:47:00来源:未知 阅读 ()
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), ]
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})
role.html:
</head> <body> <ul> {% for row in roles %} <li>{{ row.caption }}</li> {% endfor %} </ul> </body> </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_edit.html:
<body> <form method="post"> {% csrf_token %} <p>{{ form.caption }} {{ form.errors.caption.0 }}</p> <input type="submit" value="提交"> </form> </body>
user_type.html
<body> <ul> {% for row in user_type_list %} <li>{{ row.title }} - {{ row.roles.all }}</li> {% endfor %} </ul> </body>
user_type_add.html
<body> <form method="post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="提交"> </form> </body>
user_type_edit.html
<body> <form method="post" novalidate> {% csrf_token %} {{ form.as_p }} <input type="submit" value="提交"> </form> </body>
标签:
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有
- Django项目中使用qq第三方登录。 2019-08-13
- Django和前端用ajax传输json等数据 2019-08-13
- Django基本知识 2019-08-13
- JavaScript获取Django模板中指定键值的数据,使用过滤器 2019-08-13
- django框架使用及创建项目 2019-07-24
IDC资讯: 主机资讯 注册资讯 托管资讯 vps资讯 网站建设
网站运营: 建站经验 策划盈利 搜索优化 网站推广 免费资源
网络编程: Asp.Net编程 Asp编程 Php编程 Xml编程 Access Mssql Mysql 其它
服务器技术: Web服务器 Ftp服务器 Mail服务器 Dns服务器 安全防护
软件技巧: 其它软件 Word Excel Powerpoint Ghost Vista QQ空间 QQ FlashGet 迅雷
网页制作: FrontPages Dreamweaver Javascript css photoshop fireworks Flash