django之form表单与ModelForm表单
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了django之form表单与ModelForm表单相关的知识,希望对你有一定的参考价值。
1 """ 2 form表单常用属性及钩子函数示例 3 """ 4 from django import forms 5 from django.core.exceptions import ValidationError 6 7 8 class RegForm(forms.Form): 9 """ 10 注册表单 11 """ 12 username=forms.CharField(min_length=5, 13 max_length=12, 14 widget=forms.TextInput(attrs={"class":"form-control","placeholder":"username"}), 15 error_messages={"required": "请输入用户名!"}) 16 17 password=forms.CharField(widget=forms.PasswordInput(attrs={"class":"form-control","placeholder":"password"}), 18 error_messages={"required": "密码不能为空!"}) 19 20 repeat_password=forms.CharField(widget=forms.PasswordInput(attrs={"class":"form-control","placeholder":"repeat_password"}), 21 error_messages={"required": "请重复一遍密码!"}) 22 23 email=forms.EmailField(widget=forms.EmailInput(attrs={"class":"form-control","placeholder":"email"}), 24 error_messages={"required": "请输入邮箱,用于找回密码!","invalid":"邮箱格式不合法!"}) 25 26 # 验证码 27 valid_code=forms.CharField(widget=forms.TextInput(attrs={"class":"form-control","placeholder":"valid_code"}), 28 error_messages={"required":"请输入验证码!"}) 29 30 def __init__(self,request,*args): 31 self.request=request 32 forms.Form.__init__(self,*args) 33 34 def clean_username(self): 35 if self.cleaned_data["username"].isdigit() or self.cleaned_data["username"].isalpha(): 36 raise ValidationError("用户名必须包含数字与字母!") 37 else: 38 return self.cleaned_data["username"] 39 40 def clean_password(self): # 关于密码字段的钩子 41 if len(self.cleaned_data["password"])>=8: 42 return self.cleaned_data["password"] 43 else: 44 raise ValidationError("密码小于8位!") 45 46 def clean(self): 47 # print(self.cleaned_data) 48 if self.cleaned_data.get("password"): # 注意clean发生在所有验证之后 49 if self.cleaned_data["password"]==self.cleaned_data["repeat_password"]: 50 return self.cleaned_data 51 else: 52 raise ValidationError("密码不一致") 53 54 def clean_valid_code(self): 55 if self.cleaned_data["valid_code"].upper()==self.request.session.get("valid_code").upper(): 56 return self.cleaned_data["valid_code"] 57 else: 58 raise ValidationError("验证码错误!") 59 60 61 """ 62 在html页面中用{{ form_obj.as_p }}进行加载 63 """
1 """ 2 当表单项为选框时,由于form表单是取静态字段进行渲染,因此无法与数据库同步,此时在__init__方法中重写字段即可 3 """ 4 from django.forms import fields 5 6 7 class UserInfoForm(forms.Form): 8 9 name = fields.CharField(required=True,error_messages={‘required‘:‘用户名不能为空‘}) 10 11 # 此种写法不用在__init__方法中重新定义字段,但是生成的option标签value为pk,text为obj.__str__() 12 # user_type = ModelChoiceField(queryset=models.Department.objects.all()) 13 14 def __init__(self,*args,**kwargs): 15 super(UserInfoForm,self).__init__(*args,**kwargs) 16 17 self.fields[‘user_type‘].choices = models.Department.objects.values_list(‘id‘,‘title‘)
1 """ 2 ModelForm示例 3 """ 4 from django.forms import ModelForm 5 from django.forms import widgets as wid 6 from django.forms import fields as fld 7 8 9 class UserModelForm(ModelForm): 10 11 # 自定制字段 12 # user = fld.CharField() 13 14 class Meta: 15 model = models.UserInfo 16 #fields = "__all__" 17 fields = [‘username‘,‘nickname‘,] 18 exclude = [‘username‘,] # 排除字段 19 error_messages = { 20 "username": {‘required‘:‘用户名不能为空‘} 21 } 22 widgets = { 23 "username":wid.Textarea(attrs={‘class‘:‘c1‘}) 24 } 25 labels = { 26 ‘username‘:‘用户名‘ 27 } 28 help_texts = { 29 ‘username‘: ‘别瞎写,瞎写打你哦‘ 30 } 31 field_classes = { 32 ‘username‘: fld.EmailField 33 }
1 """ 2 保存 3 """ 4 obj=UserModelForm(data=request.POST) 5 if obj.is_valid(): 6 obj.save()
附:Django forms 关于select和checkbox设置初始选中值及让前端选中指定值
以上是关于django之form表单与ModelForm表单的主要内容,如果未能解决你的问题,请参考以下文章