大家好,又见面了,我是你们的朋友全栈君。
django表单:
- 渲染表单模板。
- 表单验证数据是否合法。
在App中新建的form.py表单文件:
1 from django import forms 2 from django.core import validators 3 from .models import User 4 5 # 定义form表单,label:定义名字;error_messages:定义错误时内容的提示;(例1) 6 class MesssageBoardForm(forms.Form): 7 title = forms.CharField(max_length=10,min_length=2,label='标题',error_messages={'min_length':'最小不能少于两个字符','max_length':'不能超过十个字符'}) 8 content = forms.CharField(widget=forms.Textarea,label='内容',error_messages={'required':'必须传content字段'}) 9 email = forms.EmailField(label='邮箱',error_messages={'required':'必须传email字段'}) 10 reply = forms.BooleanField(required=False,label='是否回复') 11 12 # 可简化出错信息显示的内容,通用。 13 class BaseForm(forms.Form): 14 def get_errors(self): 15 errors = self.errors.get_json_data() 16 new_errors = {} 17 for key,message_dicts in errors.items(): 18 messages = [] 19 for message_dict in message_dicts: 20 message = message_dict['message'] 21 messages.append(message) 22 new_errors[key] = messages 23 return new_errors 24 25 # 进行注册信息的简单验证表单(例2) 26 class RegisterForm(BaseForm): 27 username = forms.CharField(max_length=20,min_length=2) 28 telephone = forms.CharField(validators=[validators.RegexValidator(r'1[345678]\d{9}',message='请输入正确的手机号码!')]) 29 pwd1 = forms.CharField(max_length=16,min_length=6,error_messages={'max_length':'不能超过十六个字符','min_length':'不能小于六个字符'}) 30 pwd2 = forms.CharField(max_length=16,min_length=6,error_messages={'max_length':'不能超过十六个字符','min_length':'不能小于六个字符'}) 31 32 def clean_telephone(self): 33 telephone = self.cleaned_data.get('telephone') 34 exists = User.objects.filter(telephone=telephone).exists() 35 if exists: 36 raise forms.ValidationError(message="%s已经被注册"%telephone) 37 return telephone 38 39 def clean(self): 40 cleaned_data = super().clean() 41 pwd1 = cleaned_data.get('pwd1') 42 pwd2 = cleaned_data.get('pwd2') 43 if pwd1 != pwd2: 44 raise forms.ValidationError(message='两次密码不一致!')
视图文件:
1 from django.shortcuts import render 2 from django.views.generic import View 3 from .forms import MesssageBoardForm,RegisterForm 4 from django.http import HttpResponse 5 from .models import User 6 7 # 简单的表格格式(例1) 8 class IndexView(View): 9 # 将form传给html模板来生成一个表单的html代码; 10 # 使用form生成的代码填写格式与验证不对时会先提示,不运行; 11 def get(self,request): 12 form = MesssageBoardForm() 13 return render(request,'index.html',context={'form':form}) 14 15 # post提交时,使用form.is_valid判断提交的内容与form中定义的是否一致; 16 # cleaned_data:获取相应数据; 17 def post(self,request): 18 form = MesssageBoardForm(request.POST) 19 if form.is_valid(): 20 title = form.cleaned_data.get('title') 21 content = form.cleaned_data.get('content') 22 email = form.cleaned_data.get('email') 23 reply = form.cleaned_data.get('reply') 24 print(title) 25 print(content) 26 print(email) 27 print(reply) 28 return HttpResponse('success') 29 else: 30 # 打印出错的详细内容 31 print(form.errors.get_json_data()) 32 return HttpResponse('Fail') 33 34 # 注册信息的验证(例2) 35 class RegisterView(View): 36 # 返回注册页面模板; 37 # 不使用form的表单生成的代码,验证不对时仍会运行,没有预先提示; 38 def get(self,request): 39 return render(request,'register.html') 40 41 # 提交注册的数据 42 def post(self,request): 43 form = RegisterForm(request.POST) 44 # 验证通过 45 if form.is_valid(): 46 username = form.cleaned_data.get('username') 47 telephone = form.cleaned_data.get('telephone') 48 User.objects.create(username=username,telephone=telephone) 49 return HttpResponse('注册成功') 50 else: 51 print(form.errors.get_json_data()) 52 # 调用了BaseFrom模板后简化的出错信息; 53 print(form.get_errors()) 54 return HttpResponse('注册失败')
例1模板:
1 {# 简单的index.html模板 #} 2 <form action="" method="post"> 3 <table> 4 {{ form.as_table }} 5 <tr> 6 <td></td> 7 <td><input type="submit" value="提交"></td> 8 </tr> 9 </table> 10 </form>
例2模板:
1 {# 注册验证的模板 register.html #} 2 <form action="" method="post"> 3 <table> 4 <tr> 5 <td>用户:</td> 6 <td><input type="text" name="username"></td> 7 </tr> 8 <tr> 9 <td>电话:</td> 10 <td><input type="text" name="telephone"></td> 11 </tr> 12 <tr> 13 <td>密码:</td> 14 <td><input type="password" name="pwd1"></td> 15 </tr> 16 <tr> 17 <td>重复密码:</td> 18 <td><input type="password" name="pwd2"></td> 19 </tr> 20 <tr> 21 <td></td> 22 <td><input type="submit" value="提交"></td> 23 </tr> 24 </table> 25 </form>
例2 models.py:
1 from django.db import models 2 3 class User(models.Model): 4 username = models.CharField(max_length=20) 5 telephone = models.CharField(max_length=11)
url映射:
1 urlpatterns = [ 2 path('', views.IndexView.as_view()), 3 path('register/',views.RegisterView.as_view())
ModelForm
在表单中使用 ModelForm ,定义一个 Meta 类,如在该类中指定 model=User ,以及 fields=“__all__“ ,等于将 User 模型中所有的字段都复制过来,进行验证。则不需要在表单中重复模型中已有的字段,减少代码。
models.py文件:
1 from django.db import models 2 from django.core import validators 3 4 class User(models.Model): 5 username = models.CharField(max_length=100,validators=[validators.MinLengthValidator(2)]) 6 password = models.CharField(max_length=16,validators=[validators.MinLengthValidator(6)]) 7 telephone = models.CharField(max_length=11,validators=[validators.RegexValidator(r'1[345678]\d{9}')])
forms.py文件:
1 from django import forms 2 from .models import User 3 4 # 注册信息的验证: 5 class BaseForm(forms.ModelForm): 6 # 验证手机号是否存在; 7 def clean_telephone(self): 8 telephone = self.cleaned_data.get('telephone') 9 exists = User.objects.filter(telephone=telephone).exists() 10 if exists: 11 raise forms.ValidationError('%s手机号已存在' % telephone) 12 return telephone 13 14 # 验证用户名; 15 def clean_username(self): 16 username = self.cleaned_data.get('username') 17 exists = User.objects.filter(username=username).exists() 18 if exists: 19 raise forms.ValidationError('%s:用户名已被注册' % username) 20 return username 21 22 # 验证密码; 23 def clean(self): 24 cleaned_data = super().clean() 25 pwd1 = cleaned_data.get('pwd1') 26 pwd2 = cleaned_data.get('pwd2') 27 if pwd1 != pwd2: 28 raise forms.ValidationError('两次密码不一样') 29 else: 30 return cleaned_data 31 32 # 定义一个Meta类; 33 class RegisterForm(BaseForm): 34 pwd1 = forms.CharField(max_length=16,min_length=6,error_messages={'min_length':'不能小于6字符','max_length':'不能大于16字符'}) 35 pwd2 = forms.CharField(max_length=16,min_length=6,error_messages={'min_length':'不能小于6字符','max_length':'不能大于16字符'}) 36 37 class Meta: 38 model = User 39 # fields = ['username','telephone'] # 只提取某些字段; 40 # fields = '__all__' # 复制所有的字段; 41 exclude = ['password'] # 排除某个字段; 42 # 使用“errors_messages”定义错误信息 43 error_messages = { 44 'username':{ 45 'max_length':'不能超过100字符', 46 'min_length':'不能小于2字符' 47 }, 48 'telephone':{ 49 'invalid':'请输入正确的手机号码' 50 } 51 }
views.py文件:
1 from django.shortcuts import render 2 from django.http import HttpResponse 3 from .forms import RegisterForm 4 from django.views.decorators.http import require_POST 5 6 # 验证完成可直接调用save方法,“commit=False”:只生成模型而不插入到数据库中; 7 @require_POST 8 def register(request): 9 form = RegisterForm(request.POST) 10 if form.is_valid(): 11 user = form.save(commit=False) 12 user.password = form.cleaned_data.get('pwd1') 13 user.save() 14 return HttpResponse('success') 15 else: 16 print(form.errors.get_json_data()) 17 return HttpResponse('Fail')
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/154237.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...