django_Form组件
Posted lhqlhq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django_Form组件相关的知识,希望对你有一定的参考价值。
views文件
from django.shortcuts import render,HttpResponse,redirect # Create your views here. from django import forms from django.forms import fields class F1Form(forms.Form): user=fields.CharField( max_length=32, min_length=6, required=True, error_messages={‘required‘: ‘用户名不能为空‘, ‘max_length‘: ‘太长了‘, ‘min_length‘: ‘太短了‘, ‘invalid‘: ‘..‘} ) pwd=fields.CharField(min_length=12, required=True, error_messages={‘required‘: ‘用户名不能为空‘, ‘max_length‘: ‘太长了‘, ‘min_length‘: ‘太短了‘, ‘invalid‘: ‘..‘} ) email=fields.EmailField( required=True, min_length=8, error_messages={"required":‘邮箱不能为空‘,‘invalid‘:‘邮箱格式错误‘}) age=fields.IntegerField( required=True, error_messages={"required":‘年龄不能为空‘,‘invalid‘:‘年龄必须为数字‘} ) def f1(request): if request.method=="GET": obj=F1Form() #用来给前端添加html return render(request,‘f1.html‘,{‘obj‘:obj}) else: obj=F1Form(request.POST) if obj.is_valid(): #验证成功 print(‘验证成功‘,obj.cleaned_data) return redirect(‘http://www.baidu.com‘) else: print(‘验证失败‘,obj.errors) return render(request, ‘f1.html‘, {‘obj‘: obj})
html文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id = ‘fm‘ action="" method="post"> <p>{{ obj.user }}{{ obj.errors.user.0 }}</p> <p>{{ obj.pwd }}{{ obj.errors.pwd.0 }}</p> <p>{{ obj.email }}{{ obj.errors.email.0 }}</p> <p>{{ obj.age }}{{ obj.errors.age.0 }}</p> <input type="submit" value="提交"> <input type="button" value="ajax" onclick="submitAjaxForm()"> </form> </body> </html>
以上是关于django_Form组件的主要内容,如果未能解决你的问题,请参考以下文章