django之forms组件
以下是forms的例子,展现出forms的作用:
from django.shortcuts import render,HttpResponse # Create your views here. from django.core.exceptions import NON_FIELD_ERRORS, ValidationError from django import forms # # class BookForm(forms.Form): # title=forms.CharField(max_length=32) # price=forms.IntegerField() # email=forms.EmailField() from django.forms import widgets class UserForm(forms.Form): msg={"required":"该字段不能为空"} user=forms.CharField(min_length=5, label="用户名", error_messages=msg, widget=widgets.TextInput(attrs={"class":"form-control"}) ) pwd=forms.CharField(error_messages=msg, label="密码", min_length=5, widget=widgets.PasswordInput(attrs={"class":"form-control"}) ) r_pwd = forms.CharField(error_messages=msg, min_length=5, label="确认密码", widget=widgets.PasswordInput(attrs={"class": "form-control"}) ) email=forms.EmailField(error_messages={"invalid":"邮箱格式错误"}, label="邮箱", widget=widgets.EmailInput(attrs={"class":"form-control"}) ) ///局部钩子,可以加入自己的判断逻辑 def clean_user(self): val=self.cleaned_data.get("user") ret=UserInfo.objects.filter(user=val).first() if not ret: return val else: raise ValidationError("用户名已存在!") def clean_pwd(self): val=self.cleaned_data.get("pwd") if val.isdigit(): raise ValidationError("密码不能是纯数字!") else: return val
///全局钩子,用来判断两次密码的一致性,确认密码 def clean(self): pwd=self.cleaned_data.get("pwd") r_pwd=self.cleaned_data.get("r_pwd") if pwd and r_pwd: if pwd==r_pwd: return self.cleaned_data else: raise ValidationError("两次密码不一致!") else: return self.cleaned_data from app01.models import UserInfo def reg(request): if request.method=="POST": print(request.POST) # 数据校验 form=UserForm(request.POST) if form.is_valid(): print(form.cleaned_data) UserInfo.objects.create(**form.cleaned_data) #将所有的数据字典通过**打散,创建到表中去 return HttpResponse("OK") else: # print(form.cleaned_data) # print(form.errors) # {"user":["",]} # print(form.errors.get("user")[0]) # {"user":["",]} errors=form.errors #所有的错误 print("------>",form.errors.get("__all__")) if form.errors.get("__all__"): g_error=form.errors.get("__all__")[0] #全局钩子的错误信息 return render(request, "reg.html",locals()) else: form=UserForm() return render(request,"reg.html",locals())
reg页面:可以通过forms组件进行渲染页面,不用自己创建页面
<div class="container"> <div class="row"> <div class="col-md-8 col-md-offset-2"> <form action="" method="post" novalidate> {% csrf_token %} {% for field in form %} <div class="form-group"> <label for="">{{ field.label }}</label> {{ field }} <span class="error">{{ field.errors.0 }}</span> {% if field.label == "确认密码" %} <span class="error">{{ g_error|default:"" }}</span> {% endif %} </div> {% endfor %} <input type="reset"> <input type="submit" class="btn btn-success pull-right"> </form> </div> </div> </div>
modelfrom : https://www.cnblogs.com/DI-DIAO/p/8978780.htm