DjangoForm组件

Form组件的基础用法

 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="/form1.html" method="post">
 9     <p>{{ obj.username }}{{ obj.username.errors.0 }}</p>
10     <p>{{ obj.password }}{{ obj.password.errors.0 }}</p>
11     <p>{{ obj.email }}{{ obj.email.errors.0 }}</p>
12     <p><input type="submit" value="提交"></p>
13 </form>
14 </body>
15 </html>
Form组件基础用法HTML页面
 1 from django.shortcuts import render
 2 from django.shortcuts import HttpResponse
 3 from django.shortcuts import redirect
 4 
 5 from django import forms
 6 from django.forms import fields
 7 
 8 
 9 class myForm(forms.Form):
10     username = fields.CharField(
11         min_length=6,
12         max_length=12,
13         required=True,
14         error_messages={
15             "min_length":"用戶名太短",
16             "min_length":"用戶名太長",
17             "required":"用戶名不能為空",
18             "invalid":"用戶名格式不正确"
19         }
20     )
21     password = fields.CharField(
22         min_length=12,
23         max_length=24,
24         required=True,
25         error_messages={
26             "min_length": "密码太短",
27             "min_length": "密码太長",
28             "required": "密码不能為空",
29             "invalid": "密码格式不正确"
30         }
31     )
32     email = fields.EmailField(
33         required=True,
34         error_messages={
35             "required": "邮箱不能為空",
36             "invalid": "邮箱格式不正确"
37         }
38     )
39 
40 
41 # Create your views here.
42 def form1(request):
43     if request.method=="GET":
44         obj=myForm()
45         return render(request,"form1.html",{"obj":obj})
46     else:
47         obj=myForm(request.POST)
48         if obj.is_valid():
49             return HttpResponse("success")
50         else:
51             return render(request,"form1.html",{"obj":obj})
52     return HttpResponse("ok")
Form组件基础用法view函数

 注:默认浏览器会将自定义form类中的字段约束生效,如果想取消浏览器默认生效,可以在form表单后添加novalidate属性。

Form组件修改对象信息自动填充数据

 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="/edit_student.html?nid={{ nid }}" method="post" novalidate>
 9     <p>用户名:{{ obj.username }}{{ obj.username.errors.0 }}</p>
10     <p>邮箱:{{ obj.email }}{{ obj.email.errors.0 }}</p>
11     <p><input type="submit" value="保存"></p>
12 </form>
13 </body>
14 </html>
Form组件修改对象信息自动填充数据HTML页面
 1 from django.shortcuts import render
 2 from django.shortcuts import HttpResponse
 3 from django.shortcuts import redirect
 4 
 5 
 6 from app01.models import student
 7 from app01.former import *
 8 
 9 
10 
11 
12 
13 def edit_student(request):
14     if request.method=="GET":
15         nid=request.GET.get("nid")
16         student_obj=student.objects.filter(id=nid).first()
17         obj=userForm({"username":student_obj.username,"email":student_obj.email})
18         return render(request,"editStudent.html",{"obj":obj,"nid":nid})
19     else:
20         obj=userForm(request.POST)
21         nid=request.GET.get("nid")
22         if obj.is_valid():
23             student.objects.filter(id=nid).update(**obj.cleaned_data)
24             return redirect("/getStudent.html")
25         else:
26             return render(request,"/editStudent.html",{"obj":obj,"nid":nid})
Form组件修改对象信息自动填充数据view函数

注:form对象中可以填字典类型数据,这样在HTML页面生成HTML代码时可以将字典类型数据自动填充到页面中。

Form组件之插件使用后前台页面数据实时更新

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <h1>非诚勿扰</h1>
 9 <p>价格:{{ obj.price }}</p>
10 <p>姑娘:{{ obj.name }}</p>
11 </body>
12 </html>
Form插件之前台数据实时更新HTML页面
 1 from django.shortcuts import render,redirect,HttpResponse
 2 from django import forms
 3 from django.forms import widgets
 4 from app01.models import *
 5 import json
 6 from django.core.exceptions import NON_FIELD_ERRORS,ValidationError
 7 
 8 class LoveForm(forms.Form):
 9     price=forms.IntegerField()
10     name=forms.IntegerField(
11         widget=widgets.Select(),
12     )
13 
14     def __init__(self):
15         #super放在第一行的原因:在super父类代码中会将LoveForm中的字段放在self中,如果放在后面会造成super之前的操作self中找不到字段现象。
16         super(LoveForm, self).__init__()
17      self.fields["name"].widget.choices=User.objects.values_list("id","username")
18 
19 def love(request):
20     obj=LoveForm()
21     return render(request,"love.html",{"obj":obj})
Form插件之前台数据实时更新view函数

Form组件的对应类判断字段扩展点

 1 from django.shortcuts import render
 2 from django.shortcuts import render,redirect,HttpResponse
 3 from django import forms
 4 from django.forms import fields
 5 from django.forms import widgets
 6 from app01.models import *
 7 import json
 8 from django.core.exceptions import NON_FIELD_ERRORS,ValidationError
 9 from django.core.validators import RegexValidator
10 
11 # Create your views here.
12 
13 class cleanForm(forms.Form):
14     #1:扩展点(自定义验证规则方式一)
15     name=fields.CharField(
16         validators=[RegexValidator(r"正则表达式1","用户名格式错误"),RegexValidator(r"正则表达式2","用户名有误")]
17     )
18     #1:扩展点(自定义验证规则方式二)
19     email=fields.RegexField(
20         r"正则表达式",
21         error_messages={"invalid":"邮箱格式错误"}
22     )
23     #2:扩展点(单字段判断)
24     def clean_name(self):
25         name=self.cleaned_data["name"]
26         num=User.objects.filter(username=name).count()
27         if num:
28             raise ValidationError("用户名已存在,请重新输入!")
29         return name
30     def clean_email(self):
31         email=self.cleaned_data["email"]
32         num=User.objects.filter(email=email).count()
33         if num:
34             raise ValidationError("邮箱已存在,请重新输入!")
35         return email
36     #3:扩展点(多字段判断)
37     def clean(self):
38         v1=self.cleaned_data.get("name")
39         v2=self.cleaned_data.get("email")
40         if v1=="aa" and v2=="aa@qq.com":
41             raise ValidationError("整体错误!")
42         return self.cleaned_data
Form字段判断规则扩展点

 扩展:

1:对于整体错误信息在前端页面展示的问题:如果想在前端页面渲染整体错误信息使用{{obj.non_field_errors}}

posted @ 2020-03-12 20:23  佛祖让我来巡山  阅读(108)  评论(0编辑  收藏  举报

佛祖让我来巡山博客站 - 创建于 2018-08-15

开发工程师个人站,内容主要是网站开发方面的技术文章,大部分来自学习或工作,部分来源于网络,希望对大家有所帮助。

Bootstrap中文网