class ModelForm(forms.ModelForm): class Meta: model=models.UserInfo fields='__all__'#所有字段,列表,可以写成列表['username'] exclude=['username'] labels=None#提示消息 help_texts=None#帮助信息 widgets=None#自定义插件 error_messages=None#错误信息 field_classes=None#自定义字段类 localized_fields=('birth_date',)#本地化,不同时区显示数据,需要在setting中TIME_ZONE='Asia/Shanghai' USER_TZ=True
验证过程:is_valid->full_clean->钩子->整体错误
class UserInfoModelForm(forms.ModelForm): #可用于一个月免登录的自定义字段 is_rmb=Fields.CharField(widget=widgets.CheckboxInput()) class Meta: model=models.UserInfo fields='__all__'#所有字段,列表,可以写成列表['username'] # exclude=['username'] labels=None#提示消息 help_texts=None#帮助信息 widgets={ 'username':widgets.TextInput(attrs={'class':'c1'}) }#自定义插件 error_messages={ 'email':{ "required":"必须输入", "incalid":"格式不对", } }#错误信息 field_classes={ # "email":Fields.URLField }#自定义字段类 localized_fields=('birth_date',)#本地化,不同时区显示数据,需要在setting中TIME_ZONE='Asia/Shanghai' USER_TZ=True def clean_username(self): old=self.cleaned_data["username"] return "..." def index(request): if request.method=="GET": obj=UserInfoModelForm() return render(request,'index.html',{'obj':obj}) elif request.method=="POST": obj=UserInfoModelForm(request.POST) if obj.is_valid(): obj.save() # print(obj.is_valid()) # print(obj.cleaned_data) # print(obj.errors.as_json) # models.UserInfo.objects.create(**obj.cleaned_data)#写入数据库 return render(request,'index.html',{'obj':obj}) def user_list(request): li=models.UserInfo.objects.all().select_related("usertype") return render(request,"user_list.html",{"li":li}) def useredit(request,nid): #获取当前id用户信息并显示 if request.method=="GET": user_obj=models.UserInfo.objects.filter(id=nid).first()#获取数据 mf=UserInfoModelForm(instance=user_obj)#在页面显示数据库的信息 return render(request,"useredit.html",{"mf":mf,"nid":nid}) elif request.method=="POST": user_obj = models.UserInfo.objects.filter(id=nid).first() # 获取 mf=UserInfoModelForm(request.POST,instance=user_obj) if mf.is_valid(): #自定制字段保存cookie,session mf.save() else: print(mf.errors.as_json()) return render(request, "useredit.html", {"mf": mf, "nid": nid})