![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 ModelForm 2 a. class Meta: 3 model, # 对应Model的 4 fields=None, # 字段 5 exclude=None, # 排除字段 6 labels=None, # 提示信息 7 help_texts=None, # 帮助提示信息 8 widgets=None, # 自定义插件 9 error_messages=None, # 自定义错误信息(整体错误信息from django.core.exceptions import NON_FIELD_ERRORS) 10 field_classes=None # 自定义字段类 (也可以自定义字段) 11 localized_fields=('birth_date',) # 本地化,如:根据不同时区显示数据 12 如: 13 数据库中 14 2016-12-27 04:10:57 15 setting中的配置 16 TIME_ZONE = 'Asia/Shanghai' 17 USE_TZ = True 18 则显示: 19 2016-12-27 12:10:57 20 b. 验证执行过程 21 is_valid -> full_clean -> 钩子 -> 整体错误 22 23 c. 字典字段验证 24 def clean_字段名(self): 25 # 可以抛出异常 26 # from django.core.exceptions import ValidationError 27 return "新值" 28 d. 用于验证 29 model_form_obj = XXOOModelForm() 30 model_form_obj.is_valid() 31 model_form_obj.errors.as_json() 32 model_form_obj.clean() 33 model_form_obj.cleaned_data 34 e. 用于创建 35 model_form_obj = XXOOModelForm(request.POST) 36 #### 页面显示,并提交 ##### 37 # 默认保存多对多 38 obj = form.save(commit=True) 39 # 不做任何操作,内部定义 save_m2m(用于保存多对多) 40 obj = form.save(commit=False) 41 obj.save() # 保存单表信息 42 obj.save_m2m() # 保存关联多对多信息 43 44 f. 用于更新和初始化 45 obj = model.tb.objects.get(id=1) 46 model_form_obj = XXOOModelForm(request.POST,instance=obj) 47 ... 48 49 PS: 单纯初始化 50 model_form_obj = XXOOModelForm(initial={...})
使用modelform的增改查
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # -*- coding: utf-8 -*- 2 from __future__ import unicode_literals 3 4 from django.shortcuts import render 5 from django import forms 6 from django.forms import fields 7 from app01 import models 8 9 # Create your views here. 10 class UserInfoForm(forms.Form): 11 user = fields.CharField(max_length=32) 12 pwd = fields.CharField(max_length=32) 13 email = fields.EmailField(max_length=32) 14 usertype = fields.ChoiceField( 15 choices=models.UserType.objects.values_list('id', 'caption') 16 ) 17 def __init__(self, *args, **kwargs): 18 super(UserInfoForm, self).__init__(*args, **kwargs) 19 self.fields['usertype'].choices = models.UserType.objects.all('id', 'caption') 20 21 def index(request): 22 if request.method == 'GET': 23 obj= UserInfoForm() 24 return render(request,'index.html',{'obj':obj}) 25 if request.method =='POST': 26 obj = UserInfoForm(request.POST) 27 obj.is_valid() 28 obj.errors 29 models.UserInfo.objects.create(**obj.cleaned_data) 30 #models.UserInfo.objects.filter(id=1).update(**obj.cleaned_data) 31 return render(request,'index.html',{'obj':obj})
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # -*- coding: utf-8 -*- 2 from __future__ import unicode_literals 3 4 from django.shortcuts import render 5 from django import forms 6 from django.forms import fields as Ffields 7 from django.forms import widgets as Fwidegets 8 from app01 import models 9 10 # Create your views here. 11 class UserInfoModelForm(forms.ModelForm): 12 is_rem = Ffields.CharField( 13 widget=Fwidegets.CheckboxInput() 14 ) 15 class Meta: 16 model = models.UserInfo 17 fields = '__all__' 18 #fields = ['username','pwd'] 选取 19 #exclude = ['username'] 排除 20 labels = { 21 'user':'用户名', 22 'pwd':'密码', 23 'email':'邮箱', 24 } 25 help_texts = { 26 'user':'111111' 27 } 28 # widgets={ 29 # 'user':Fwidegets.Textarea(attrs={'style':'background-color:blue'}) 30 # } 31 error_messages={ 32 '__all__':{ 33 34 }, 35 'user':{'required':'用户名不能为空'} 36 } 37 # field_classes={ 38 # 'email':Ffields.URLField 39 # } 40 def clean_username(self): 41 old = self.cleaned_data['user'] 42 print 'old is :',old 43 return old 44 45 46 def index(request): 47 if request.method == 'GET': 48 obj= UserInfoModelForm() 49 return render(request,'index.html',{'obj':obj}) 50 51 if request.method =='POST': 52 obj = UserInfoModelForm(request.POST) 53 if obj.is_valid(): 54 obj.save() 55 # instance=obj.save(False) 等价于obj.save() 56 # instance.save() 57 # obj.save_m2m() 58 59 # print obj.is_valid() 60 # print obj.cleaned_data 61 # print obj.errors 62 63 # models.UserInfo.objects.create(**obj.cleaned_data) 64 #models.UserInfo.objects.filter(id=1).update(**obj.cleaned_data) 65 return render(request,'index.html',{'obj':obj}) 66 67 def user_list(request): 68 li = models.UserInfo.objects.all().select_related('usertype') 69 return render(request,'user_list.html',{'li':li}) 70 71 def user_edit(request,nid): 72 #获取当前的id的信息 73 #显示用户已经存在信息 74 if request.method=="GET": 75 user_obj=models.UserInfo.objects.filter(id=nid).first() 76 mf=UserInfoModelForm(instance=user_obj) 77 return render(request, 'user_edit.html', {'mf':mf,'nid': nid}) 78 if request.method=="POST": 79 user_obj = models.UserInfo.objects.filter(id=nid).first() 80 mf=UserInfoModelForm(request.POST,instance=user_obj) 81 if mf.is_valid(): 82 mf.save() 83 else: 84 print mf.errors 85 return render(request, 'user_edit.html', {'mf': mf, 'nid': nid})
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # -*- coding: utf-8 -*- 2 from __future__ import unicode_literals 3 4 from django.db import models 5 6 # Create your models here. 7 8 class UserType(models.Model): 9 caption=models.CharField(max_length=32) 10 11 def __unicode__(self): 12 return self.caption 13 14 class UserGroup(models.Model): 15 name=models.CharField(max_length=32) 16 17 def __unicode__(self): 18 return self.name 19 20 class UserInfo(models.Model): 21 user = models.CharField(max_length=32) 22 pwd = models.CharField(max_length=32) 23 email = models.EmailField(max_length=32) 24 usertype=models.ForeignKey(to='UserType',to_field='id') 25 u2g=models.ManyToManyField(UserGroup)
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <form action="/index/" method="POST"> 9 {% csrf_token %} 10 {{ obj.as_p }} 11 <p><input type="submit" value="提交"> </p> 12 </form> 13 </body> 14 </html>
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/edit-{{ nid }}/" method="POST"> {% csrf_token %} {{ mf.as_p }} <p><input type="submit" value="提交"></p> </form> </body> </html>
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <ul> 9 {% for row in li %} 10 <li>{{ row.user }} - {{ row.usertype.caption}}--<a href="/edit-{{ row.id }}/">编辑</a></li> 11 {% endfor %} 12 </ul> 13 </body> 14 </html>