首页 技术 正文
技术 2022年11月18日
0 收藏 735 点赞 4,339 浏览 5769 个字

form 组件的使用

内置组件

Field
required=True, 是否允许为空
widget=None, HTML插件
label=None, 用于生成Label标签或显示内容
initial=None, 初始值
help_text='', 帮助信息(在标签旁边显示)
error_messages=None, 错误信息 {'required': '不能为空', 'invalid': '格式错误'}
show_hidden_initial=False, 是否在当前插件后面再加一个隐藏的且具有默认值的插件(可用于检验两次输入是否一直)
validators=[], 自定义验证规则
localize=False, 是否支持本地化
disabled=False, 是否可以编辑
label_suffix=None Label内容后缀CharField(Field)
max_length=None, 最大长度
min_length=None, 最小长度
strip=True 是否移除用户输入空白IntegerField(Field)
max_value=None, 最大值
min_value=None, 最小值FloatField(IntegerField)
...DecimalField(IntegerField)
max_value=None, 最大值
min_value=None, 最小值
max_digits=None, 总长度
decimal_places=None, 小数位长度BaseTemporalField(Field)
input_formats=None 时间格式化 DateField(BaseTemporalField) 格式:2015-09-01
TimeField(BaseTemporalField) 格式:11:12
DateTimeField(BaseTemporalField)格式:2015-09-01 11:12DurationField(Field) 时间间隔:%d %H:%M:%S.%f
...RegexField(CharField)
regex, 自定制正则表达式
max_length=None, 最大长度
min_length=None, 最小长度
error_message=None, 忽略,错误信息使用 error_messages={'invalid': '...'}EmailField(CharField)
...FileField(Field)
allow_empty_file=False 是否允许空文件ImageField(FileField)
...
注:需要PIL模块,pip3 install Pillow
以上两个字典使用时,需要注意两点:
- form表单中 enctype="multipart/form-data"
- view函数中 obj = MyForm(request.POST, request.FILES)URLField(Field)
...BooleanField(Field)
...NullBooleanField(BooleanField)
...ChoiceField(Field)
...
choices=(), 选项,如:choices = ((0,'上海'),(1,'北京'),)
required=True, 是否必填
widget=None, 插件,默认select插件
label=None, Label内容
initial=None, 初始值
help_text='', 帮助提示ModelChoiceField(ChoiceField)
... django.forms.models.ModelChoiceField
queryset, # 查询数据库中的数据 =Book.object.all()
empty_label="---------", # 默认空显示内容
to_field_name=None, # HTML中value的值对应的字段
limit_choices_to=None # ModelForm中对queryset二次筛选ModelMultipleChoiceField(ModelChoiceField)
... django.forms.models.ModelMultipleChoiceFieldTypedChoiceField(ChoiceField)
coerce = lambda val: val 对选中的值进行一次转换
empty_value= '' 空值的默认值MultipleChoiceField(ChoiceField)
...TypedMultipleChoiceField(MultipleChoiceField)
coerce = lambda val: val 对选中的每一个值进行一次转换
empty_value= '' 空值的默认值ComboField(Field)
fields=() 使用多个验证,如下:即验证最大长度20,又验证邮箱格式
fields.ComboField(fields=[fields.CharField(max_length=20), fields.EmailField(),])MultiValueField(Field)
PS: 抽象类,子类中可以实现聚合多个字典去匹配一个值,要配合MultiWidget使用SplitDateTimeField(MultiValueField)
input_date_formats=None, 格式列表:['%Y--%m--%d', '%m%d/%Y', '%m/%d/%y']
input_time_formats=None 格式列表:['%H:%M:%S', '%H:%M:%S.%f', '%H:%M']FilePathField(ChoiceField) 文件选项,目录下文件显示在页面中
path, 文件夹路径
match=None, 正则匹配
recursive=False, 递归下面的文件夹
allow_files=True, 允许文件
allow_folders=False, 允许文件夹
required=True,
widget=None,
label=None,
initial=None,
help_text=''GenericIPAddressField
protocol='both', both,ipv4,ipv6支持的IP格式
unpack_ipv4=False 解析ipv4地址,如果是::ffff:192.0.2.1时候,可解析为192.0.2.1, PS:protocol必须为both才能启用SlugField(CharField) 数字,字母,下划线,减号(连字符)
...UUIDField(CharField) uuid类型
...
class Register(forms.Form):
user = forms.CharField(min_length=2, widget=widgets.TextInput(attrs={'class': 'form-control'}),
label='用户名',
error_messages={'required': "参数错误", 'invalid': '输入的用户名格式错误'}) pwd = forms.CharField(widget=widgets.PasswordInput(attrs={'class': 'form-control'}),
label='密码',
error_messages={'required': "参数错误", 'invalid': '输入的密码格式错误'})
r_pwd = forms.CharField(widget=widgets.PasswordInput(attrs={'class': 'form-control'}),
label='确认密码',
error_messages={'required': "参数错误", 'invalid': '输入的密码格式错误'})
email = forms.EmailField(widget=widgets.EmailInput(attrs={'class': 'form-control'}),
label='邮箱',
error_messages={'required': "参数错误", 'invalid': '输入的邮箱格式错误'}) def clean_user(self):
print(self.data)
user = self.cleaned_data.get('user')
ret = Users.objects.filter(user=user).first()
if not ret:
return user
else:
raise ValidationError('用户名存在') 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('两次密码不一致')
return self.cleaned_data 

逻辑代码

def regist(request):
form = Register()
if request.method == 'GET':
return render(request, 'reg.html', locals())
else:
form = Register(request.POST) if form.is_valid():
print(form.cleaned_data)
Users.objects.create(**form.cleaned_data) else:
print(form.cleaned_data)
errors = form.errors
return render(request, 'reg.html', locals()) return HttpResponse('ok')

模板渲染

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title>
<style>
.demo {
color: red;
margin-left: 15px;
} .error {
color: red;
margin-left: 12px;
}
</style>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="external nofollow"
integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"></head>
<body>
{# 方式1 #}
{#<form action="" method="post">#}
{# {% csrf_token %}#}
{# <p>用户名:<input type="text" name="user"><span class="demo">{{ errors.user.0 }}</span></p>#}
{# <p>密码:<input type="password" name="pwd"><span class="demo">{{ errors.pwd.0 }}</span></p>#}
{# <p>邮箱:<input type="text" name="email"><span class="demo">{{ errors.email.0 }}</span></p>#}
{# <p><input type="submit" value="提交"></p>#}
{#</form>#}<hr>{# 方式2 #}
{#<form action="" method="post">#}
{# {% csrf_token %}#}
{# {{ form.as_p }}#}
{# <p><input type="submit" value="提交"></p>#}
{#</form>#}
{#方式3 #}
<hr>
{#<div class="container">#}
{# <div class="row">#}
{# <div class="col-md-8 col-md-offset-2">#}
{# <form action="" method="post" novalidate>#}
{# {% csrf_token %}#}
{# <p> 用户名 {{ form.user }}<span class="error">{{ errors.user.0 }}</span></p>#}
{# <p>密码 {{ form.pwd }}<span class="error">{{ errors.pwd.0 }}</span></p>#}
{# <p>邮箱 {{ form.email }}<span class="error">{{ errors.email.0 }}</span></p>#}
{##}
{# <input type="submit" class="btn btn-success pull-right">#}
{# </form>#}
{# </div>#}
{# </div>#}
{#</div>#}
<hr>
{# 方式4 #}
<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 %}
<p> {{ field.label }} {{ field }}<span class="error">{{ field.errors.0 }}</span></p>
{% endfor %}
<input type="submit" class="btn btn-success pull-right">
</form>
</div>
</div>
</div></body>
</html>
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,492
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,493
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,294