- 初始form组件
Django的Form主要具有一下几大功能:
- 生成HTML标签
- 验证用户数据(显示错误信息)
- HTML Form提交保留上次提交数据
- 初始化页面显示内容
- 验证功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form method="post" action="/form/">
<P><input type="text" name="username">{{ obj.errors.username.0 }}</P>
<P><input type="password" name="pwd">{{ obj.errors.pwd.0 }}</P>
<P><input type="text" name="age">{{ obj.errors.age.0 }}</P>
<P><input type="text" name="email">{{ obj.errors.email.0 }}</P>
<p><input type="submit"></p>
</form>
</body>
</html>
from django import forms from django.forms import fields class RegisterForm(forms.Form): username = forms.CharField(max_length=20, min_length=6, required=True, error_messages={ ‘required‘:‘用户名不能为空‘, ‘max_length‘: ‘最大长度20‘, ‘min_length‘: ‘最小长度6‘, }) pwd = forms.CharField(max_length=20, min_length=6, required=True) age = forms.IntegerField(required=True) email = forms.EmailField(required=True,error_messages={ ‘invalid‘:‘格式错误‘ })
from django.shortcuts import render from myform.cfrom import RegisterForm # Create your views here. def form(request): if request.method == ‘GET‘: return render(request, ‘forms/index.html‘) else: print(request.POST) obj = RegisterForm(request.POST) if obj.is_valid(): print(obj.cleaned_data) else: print(obj.errors) return render(request, ‘forms/index.html‘,{‘obj‘:obj})
- 生成input标签功能
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form method="post" action="/form/" novalidate> <P>{{ form_obj.username }}{{ form_obj.errors.username.0 }}</P> <P>{{ form_obj.pwd }}{{ form_obj.errors.pwd.0 }}</P> <P>{{ form_obj.age }}{{ form_obj.errors.age.0 }}</P> <P>{{ form_obj.email }}{{ form_obj.errors.email.0 }}</P> <p><input type="submit"></p> </form> </body> </html>
from django.shortcuts import render
from myform.cfrom import RegisterForm
# Create your views here.
def form(request):
if request.method == ‘GET‘:
form_obj = RegisterForm()
return render(request, ‘forms/index.html‘, {‘form_obj‘: form_obj})
else:
print(request.POST)
form_obj = RegisterForm(request.POST)
# obj = RegisterForm(request.POST)
if form_obj.is_valid():
print(form_obj.cleaned_data)
else:
print(form_obj.errors)
return render(request, ‘forms/index.html‘, { ‘form_obj‘: form_obj})
form类
from django import forms from django.forms import fields from django.forms import widgets class RegisterForm(forms.Form): username = fields.CharField( max_length=20, min_length=6, required=True, widget=widgets.TextInput(attrs={‘v‘: ‘v1‘, ‘class‘: ‘c1‘}), initial=‘用户名‘, label=‘用户名‘, help_text=‘字母、数字、下划线‘, disabled=False, label_suffix=‘:‘, error_messages={ ‘required‘: ‘用户名不能为空‘, ‘max_length‘: ‘最大长度20‘, ‘min_length‘: ‘最小长度6‘, }, ) pwd = fields.CharField( max_length=20, min_length=6, required=True, label=‘密码‘, widget=widgets.PasswordInput ) age = fields.IntegerField( required=True, max_value=200, min_value=0, label=‘年龄‘, ) email = fields.EmailField(required=True, error_messages={ ‘invalid‘: ‘格式错误‘ }, label=‘邮箱‘, ) # 单选select city = fields.ChoiceField( choices=[ (1, ‘中国‘), (2, ‘美国‘), (3, ‘日本‘), ], initial=1, label=‘国籍‘, ) # 多选select hobby = fields.MultipleChoiceField( choices=[ (1, ‘音乐‘), (2, ‘把妹‘), (3, ‘约妹‘), ], initial=[1, 3] ) def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) # 必须在self.fieLds上面 self.fields[‘hobby‘].widget.choices = ((1, ‘嗨‘), (2, ‘嗨嗨‘),) # 或 # self.fields[‘hobby‘].widget.choices = models.Classes.objects.all().value_list(‘id‘, ‘caption‘) # 文件 img = fields.FileField( label=‘图片‘ ) # 单选的checkbox chk = fields.CharField( widget=widgets.CheckboxInput( attrs={‘v‘: ‘v1‘, ‘class‘: ‘c1‘} ), label=‘居住地‘ ) # 多选checkbox,值为列表 dchk = fields.MultipleChoiceField( initial=[2, 1], choices=((1, ‘上海‘), (2, ‘北京‘),), widget=widgets.CheckboxSelectMultiple, label=‘曾住地‘ ) # 单选的radio rad = fields.CharField( widget=widgets.RadioSelect(choices=((1, ‘男‘), (2, ‘女‘),)), label=‘性别‘ ) # 单radio,值为字符串 rad1 = fields.ChoiceField( choices=((1, ‘有‘), (2, ‘无‘),), initial=2, widget=widgets.RadioSelect( attrs={‘class‘: ‘ll‘} ), label=‘媳妇‘ )