Form组件
Django框架基础之Form组件
服务端假设所有用户提交的数据都是不可信任的,所以Django框架内置了form组件来验证用户提交的信息
form组件的2大功能:
1 验证(显示错误信息)
2 保留用户上次输入的信息
-- 可以生成html标签
示例
html4
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>欢迎注册</title> <link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.css"> <link rel="stylesheet" href="/static/css/bbs.css"> </head> <body> {% csrf_token %} <div class="container"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <form class="login-form"> <div class="form-group"> <label for="{{ form_obj.username.id_for_label }}">{{ form_obj.username.label }}</label> {{ form_obj.username }} <span class="help-block"></span> </div> <div class="form-group"> <label for="{{ form_obj.password.id_for_label }}">{{ form_obj.password.label }}</label> {{ form_obj.password }} <span class="help-block"></span> </div> <div class="form-group"> <label for="{{ form_obj.re_password.id_for_label }}">{{ form_obj.re_password.label }}</label> {{ form_obj.re_password }} <span class="help-block"></span> </div> <div class="form-group"> <label for="{{ form_obj.phone.id_for_label }}">{{ form_obj.phone.label }}</label> {{ form_obj.phone }} <span class="help-block"></span> </div> <div class="form-group"> <label for="{{ form_obj.email.id_for_label }}">{{ form_obj.email.label }}</label> {{ form_obj.email }} <span class="help-block"></span> </div> <div class="form-group"> <label for="avatar">头像<img id="avatar-img" src="/static/default.png" alt="" style="height: 80px;width: 80px;margin-left: 15px"></label> <input type="file" accept="image/*" id="avatar" style="display: none;"> </div> <div class="form-group"> <label for="v-code" style="display: block;">验证码</label> <input type="text" id="v-code" class="form-control" style="width: 250px;display: inline-block"> <img src="/v-code/" id="i1" style="float: right"> <span id="error-p" class="err-text"></span> </div> <button id="reg-btn" type="button" class="btn btn-default">注册</button> </form> </div> </div> </div> <script src="/static/js/jquery.js"></script> <script> $("#reg-btn").click(function () { // 1. 取到用户填写的数据 var fd = new FormData(); fd.append("username", $("#id_username").val()); fd.append("password", $("#id_password").val()); fd.append("re_password", $("#id_re_password").val()); fd.append("phone", $("#id_phone").val()); fd.append("email", $("#id_email").val()); fd.append("v_code", $("#v-code").val()); fd.append("csrfmiddlewaretoken", $("[name='csrfmiddlewaretoken']").val()); fd.append('avatar', $("#avatar")[0].files[0]); // 2. 往后端发post请求 $.ajax({ url: '/reg/', type: 'post', data: fd, processData: false, contentType: false, success:function (res) { console.log(res); if (res.code === 2){ // 验证码有错误 $("#error-p").text(res.msg); }else if (res.code === 0){ // 注册成功 location.href = res.msg; }else if (res.code === 1){ console.log(res.msg); // 遍历取出所有的错误提示信息,在页面上展示出来 $.each(res.msg, function (k,v) { $("#id_"+k).next().text(v[0]).parent().addClass('has-error'); }) } } }) }); // 每一个input标签获取焦点的时候,把自己下面的span标签内容清空,把父标签的has-error样式移除 $("input.form-control").focus(function () { $(this).val('').next("span").text('').parent().removeClass('has-error'); }); $("#v-code").focus(function () { $(this).val('').next().next().text(''); }); // 前端页面实现头像预览 // 当用户选中文件之后,也就是头像的input标签有值时触发 $("#avatar").change(function () { // 找到用户选中的那个文件 var file = this.files[0]; // 生成一个读文件的对象 var fr = new FileReader(); // 从文件中读取头像文件数据 fr.readAsDataURL(file); // 等到读完之后 fr.onload = function () { // 将头像img标签的src属性更换成我选中的那个文件 $("#avatar-img").attr("src", fr.result) } }) </script> </body> </html>
forms
from django import forms from django.core.validators import RegexValidator from django.core.exceptions import ValidationError # 注册 class RegisterForm(forms.Form): username = forms.CharField( label= '用户名', min_length=4, error_messages={ "required":"用户名不能为空", "min_length":"用户名不能少于4位" }, widget=forms.widgets.TextInput( attrs={"class" : "form-control"} ) ) password = forms.CharField( label='密码', min_length=6, error_messages= { "required":"密码不能位空", "min_length":"密码不能少于6位" }, widget = forms.widgets.PasswordInput( attrs={"class":"form-control"} ) ) re_password = forms.CharField( label= "确认密码", min_length=6, error_messages={ "required":"密码不能为空", "min_length":"密码不能少于6位" }, widget=forms.widgets.PasswordInput( attrs = {'class':'form-control'} ) ) phone = forms.CharField( label= "手机号", error_messages={ "required":"手机号不能为空" }, validators = [RegexValidator(r'1[3-9]\d{9}',"手机号码格式不正确")], widget=forms.widgets.TextInput( attrs={"class": "form-control"} ) ) email = forms.CharField( label= "邮箱", error_messages={ "required":"邮箱不能未空" }, validators=[RegexValidator(r'^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$',"邮箱格式不正确")], widget = forms.widgets.EmailInput( attrs = {"class": "form-control"} ) ) def clean(self): pwd = self.cleaned_data.get('password') re_pwd = self.cleaned_data.get('re_password') if re_pwd and re_pwd == pwd: return self.cleaned_data else:self.add_error('re_password','两次密码不一致') raise ValidationError("两次密码不一致")
views
from django.shortcuts import render from blog.forms import RegisterForm from django.http import JsonResponse from blog import models # Create your views here. def home(request): return render(request,'home.html') def register(request): form_obj = RegisterForm(request.POST) if request.method == 'POST': res = {"code":0} print(request.POST) if form_obj.is_valid(): print(1) print(form_obj.cleaned_data) form_obj.cleaned_data.pop('re_password') models.UserInfo.objects.create(**form_obj.cleaned_data) res['msg'] = '/login/' else: print(1) res["code"] = 1 print(form_obj.errors) res['msg'] = form_obj.errors return JsonResponse(res) return render(request,'register.html',{"form_obj":form_obj})