生成 html 代码
- views.py
from django import forms, views
class BookForm(forms.Form):
title = forms.CharField(
max_length=16,
label="书名",
widget=forms.TextInput(
attrs={
"class": "form-control",
"placeholder": "此处填写书名",
}
)
)
class BookAdd(views.View):
def get(self):
form_obj = BookForm()
return render(request, "book_add.html", locals())
- book_add.html
<form action="" method="post" novalidate autocomplete="off">
{% csrf_token %}
<div class="col-md-8 col-md-offset-2">
{% for foo in form_obj %}
<div class="form-group">
<label for="{{ foo.id_for_label }}">{{ foo.label }}</label>
{{ foo }}
<p style="color: red">{{ foo.errors.0 }}</p>
</div>
{% endfor %}
<input type="submit" value="提交" class="btn btn-success">
</div>
</form>
校验规则
参数校验
class PersonForm(forms.Form):
name = forms.CharField(
max_length=16,
label="姓名",
)
age = forms.IntegerField(
required=False
)
phone = forms.CharField(
min_length=11,
max_length=11,
)
正则校验
from django.core.validators import RegexValidator
class BookForm(forms.Form):
phone = forms.CharField(
validators=[RegexValidator(r'^1[356789]\d{9}$', "手机号码格式有误")]
)
自定义校验
from django.core.validators import RegexValidator
from django.core.exceptions import ValidationError
def phone_validate(value):
is_exist = models.Book.objects.filter(phone=value)
if is_exist:
raise ValidationError("该手机号已经注册")
else:
return value
class BookForm(forms.Form):
phone = forms.CharField(
validators=[RegexValidator(r'^1[356789]\d{9}$', "手机号码格式有误"), phone_validate]
)
Hook 校验
class BookForm(forms.Form):
title = forms.CharField(
max_length=12,
label="书名",
)
pwd1 = forms.CharField(
label="pwd-1",
widget=forms.PasswordInput(
attrs={
"class": "form-control"
}
)
)
pwd2 = forms.CharField(
label="pwd-2",
widget=forms.PasswordInput(
attrs={
"class": "form-control"
}
)
)
def clean_title(self):
v = self.cleaned_data.get("title")
if "alex" in v:
raise ValidationError("包含敏感词 alex")
else:
return v
def clean(self):
pwd1 = self.cleaned_data.get("pwd1")
pwd2 = self.cleaned_data.get("pwd2")
if pwd1 != pwd2:
self.add_error("pwd2", "密码不相同")
else:
pass