1、Model 强大的数据库操作,弱小的数据验证
    a. 表
      一对多:
          to
          to_fields
          related_name
          related_query_name
          on_delete
          limit_choices_to

          ......  
    b. 操作
          create
          ......
    c. 验证
          full_clean -> 字段正则判定 --> clean方法(钩子)

2、Form 强大的数据验证
      is_valid() -> full_clean()   -> 每个字段的正则,每个字段的方法 clean_字段名()
                  -> _clean_form -> clean(钩子)
                  -> _post_clean(钩子)
      ===》返回值is_valid()
      cleaned_data
      errors
      ==》 实时显示新插入的数据

 1 from django.shortcuts import render
 2 from django.forms import widgets,fields,Form,models as models_fields
 3 from django.core.exceptions import ValidationError
 4 from app01 import models
 5 class UserForm(Form):
 6     username = fields.CharField(label='用户名')
 7     email = fields.EmailField(label='邮箱')
 8     # 显示同数据库实时更新方式一(配合下面的init)
 9     user_type1 = fields.ChoiceField(choices=models.UserType.objects.values_list('id','name'))
10     # 显示同数据库实时更新方式二
11     user_type2 = models_fields.ModelChoiceField(queryset=models.UserType.objects.all(),
12                                                 empty_label='请选择用户类型',
13                                                 to_field_name="id",
14                                                 limit_choices_to={'id':1})
15     user_type3 = models_fields.ModelMultipleChoiceField(queryset=models.UserType.objects.all(),
16                                                 to_field_name="id",
17                                                 limit_choices_to={'id': 1})
18     def __init__(self,*args,**kwargs):
19         super(UserForm,self).__init__(*args,**kwargs)
20         self.fields['user_type1'].widget.choices = models.UserType.objects.all().values_list('id', 'name')
21     #通过钩子函数自定义错误
22     def clean_username(self):
23         #
24         value = self.cleaned_data['username']
25         if value == 'root':
26             return value
27         else:
28             raise ValidationError('你不是我的...')
29     def clean(self):
30         v1 = self.cleaned_data['username']
31         v2 = self.cleaned_data['email']
32         if v1 == "root" and v2 == "root@live.com":
33             pass
34         else:
35             raise ValidationError('用户名或邮箱错误!!!')
36         return self.cleaned_data
37     # def _post_clean(self):
38     #     v1 = self.cleaned_data['username']
39     #     v2 = self.cleaned_data['email']
40     #     if v1 == "root" and v2 == "root@live.com":
41     #         pass
42     #     else:
43     #         self.add_error("__all__", ValidationError('用户名或邮箱错误...'))
44 
45 def index(request):
46     if request.method == "GET":
47         obj = UserForm()
48         return render(request,'fm.html',{'obj': obj})
49     elif request.method == "POST":
50         obj = UserForm(request.POST)
51         obj.is_valid()
52         # data = obj.clean()
53         # obj.cleaned_data
54         # print(obj.errors)
55         return render(request, 'fm.html', {'obj': obj})
56 
57 def test(request):
58     # obj = models.News.objects.create()
59     obj = models.News(title='root_12')
60     obj.full_clean()
61     obj.save()
显示同数据库实时更新两种方式与通过钩子函数自定义错误

 

3、ModelForm 强大的数据验证,适中的数据库操作
    Form: UserForm -> Form -> BaseForm
    ModelForm: UserModelForm -> ModelForm -> BaseModelForm -> BaseForm

 1 mf.py
 2 
 3 from django.shortcuts import render
 4 from django.forms import ModelForm
 5 from app01 import models
 6 class UserModelForm(ModelForm):
 7     class Meta:
 8         model = models.User
 9         fields = "__all__"
10 #modelform创建信息自动存进数据库
11 def index(request):
12     if request.method == "GET":
13         obj = UserModelForm()
14         return render(request,'mf.html',{'obj': obj})
15     elif request.method == "POST":
16         obj = UserModelForm(request.POST)
17         if obj.is_valid():
18             # print(obj.cleaned_data)
19             # models.User.objects.create(**obj.cleaned_data)
20             obj.save(commit=True)#创建的信息自动存进数据库(默认commit=True,相当于下面三句)
21             """
22             mobj = obj.save(commit=False)
23             mobj.save()
24             obj.save_m2m()
25             """
26         print(obj.errors)
27         return render(request, 'mf.html', {'obj': obj})
28 #modelform实现数据库信息更新
29 def edit_index(request,nid):
30     if request.method == "GET":
31         model_obj = models.User.objects.get(id=nid)
32         obj =UserModelForm(instance=model_obj)
33         return render(request, 'mf1.html', {'obj': obj,'nid': nid})
34     elif request.method == 'POST':
35         model_obj = models.User.objects.get(id=nid)
36         obj = UserModelForm(request.POST, instance=model_obj)
37         if obj.is_valid():
38             obj.save()
39         return render(request, 'mf1.html', {'obj': obj})
40 
41 
42 urls.py
43 
44 from django.conf.urls import url
45 from django.contrib import admin
46 from app01.views import orm,fm,mf
47 urlpatterns = [
48     url(r'^admin/', admin.site.urls),
49     url(r'^index/', orm.index),
50     url(r'^fm/', fm.index),
51     url(r'^mf/', mf.index),
52     url(r'^edit-mf-(\d+)/', mf.edit_index),
53 ]
54 
55 
56 mf.html
57 
58 <body>
59     <form action="/mf/" method="POST">
60     {{ obj.as_p }}
61         <input type="submit" value="提交" />
62     </form>
63 </body>
64 
65 
66 mf1.html
67 
68 <body>
69     <form action="/edit-mf-{{nid}}/" method="POST">
70         {{ obj.as_p }}
71         <input type="submit" value="提交" />
72     </form>
73 </body>
modelform创建信息自动存进数据库,modelform实现数据库信息更新

 

posted on 2019-06-19 23:29  始终不够啊  阅读(145)  评论(0编辑  收藏  举报