1.前端form表单模板代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Login</title> </head> <body> <form action="/login/" method="post"> {% csrf_token %} {{obj.user}}<span>{{obj.errors.user.0}}</span> <br> {{obj.email}}<span>{{obj.errors.email.0}}</span> <br> <span>密码</span><input type="text" name="password"> <br> <input type="submit"> </form> </body> </html>
2.后台数据Python代码对前端的form表单数据进行校验
1 from django.shortcuts import render, HttpResponse, redirect 2 from django import forms 3 4 # Create your views here. 5 class Login(forms.Form): 6 user = forms.CharField(min_length=6, error_messages={'required': '用户名不能为空', 'min_length': '用户名不能小于6位'}) 7 email = forms.EmailField(error_messages={'required': '邮箱不能为空', 'invalid': '邮箱格式错误'}) 8 #此处未定义password,会导致下面的Login对象在接收前台数据时,只接收user数据和password数据 9 10 def login(request): 11 if request.method == 'GET': 12 obj = Login() 13 return render(request, 'login.html', {'obj': obj}) 14 else: 15 obj = Login(request.POST) 16 if obj.is_valid():#is_valid()用于判断obj对象是否校验通过,校验通过传回true 17 value_list = obj.clean()#clean()用于获取obj中已校验通过的数据 18 print(value_list) 19 #create(**value_list)#可直接将获取到的对象的值通过该方式插入到数据库中 20 else: 21 #error_obj = obj.errors.as_json()#获取校验失败的信息 22 error_obj = obj.errors #获取错误对象 23 print(error_obj['user'][0])#获取user中文错误信息 24 print(error_obj['email'][0])#获取email中文错误信息 25 #print(error_obj) 26 return render(request, 'login.html', {'obj': obj})
3.通过django生成前端form表单时,可以通过widget自定义input输入框的类型,并给它赋予前端属性
1 from django import forms 2 from django.forms import fields 3 from django.forms import widgets 4 5 class LoginForm(forms.Form): 6 user = fields.CharField(widget=widgets.TextInput(attrs={'class': 'hid', 'placeholder': '用户名'})) 7 #CharField的默认类型为TextInput,此处加上只是为了给当前input输入框增加属性attrs={'class': 'hid', 'placeholder': '用户名'} 8 password = fields.CharField(widget=widgets.PasswordInput(attrs={'class': 'hid', 'placeholder': '密码'})) 9 #CharField的默认类型为TextInput,加上widget=widgets.PasswordInput后变成password类型输入框 10 select = fields.ChoiceField(choices=[(1, 'SH'), (2, 'BJ'), ]) 11 #利用choices=[(1, 'SH'), (2, 'BJ'), ]给前端下拉列表增加可选值
4.通过models中的class类生成对应的form表单
1 from django import forms 2 from app01 import models #导入表模型类 3 class UserInfoModelForm(forms.ModelForm): 4 class Meta: 5 model = models.Test #test为models中的一个类 6 #fields = ('username',) 7 fields = '__all__'