{{ form.as_table }} 以表格的形式将它们渲染在<tr> 标签中
{{ form.as_p }} 将它们渲染在<p> 标签中
{{ form.as_ul }} 将它们渲染在<li> 标签中
 <form action="" method="post" novalidate>
{% csrf_token %}
<p>{{ form.name.label }}
{{ form.name }}
<span class="pull-right error">{{ form.name.errors.0 }}</span>
</p>
<p>{{ form.pwd.label }}
{{ form.pwd }}
<span class="pull-right error">{{ form.pwd.errors.0 }}</span>
</p>
<p>确认密码
{{ form.r_pwd }}
<span class="pull-right error">{{ form.r_pwd.errors.0 }}</span>
<span class="pull-right error">{{ errors.0 }}</span>
</p>
<p>邮箱 {{ form.email }}
<span class="pull-right error">{{ form.email.errors.0 }}</span>
</p>
<p>手机号 {{ form.tel }}
<span class="pull-right error">{{ form.tel.errors.0 }}</span>
</p>
<input type="submit">
</form>
 def reg(request):
if request.method == "POST":
form = UserForm(request.POST) # form表单的name属性值应该与forms组件字段名称一致
if form.is_valid():
print(form.cleaned_data) # {"name":"yuan","email":"123@qq.com"}  经过检验通过的字段的值的字典
else:
print(form.cleaned_data) # {"email":"123@qq.com"}
errors = form.errors.get("__all__")# 全局错误信息列表
return render(request, "reg.html", locals())
form = UserForm()
return render(request, "reg.html", locals())
 from django import forms
from django.forms import widgets
from app01.models import UserInfo from django.core.exceptions import ValidationError class UserForm(forms.Form):
name = forms.CharField(min_length=4, label="用户名", error_messages={"required": "该字段不能为空"},
widget=widgets.TextInput(attrs={"class": "form-control"}),initial="张三",
)
pwd = forms.CharField(min_length=4, label="密码",
widget=widgets.PasswordInput(attrs={"class": "form-control"})
)
r_pwd = forms.CharField(min_length=4, label="确认密码", error_messages={"required": "该字段不能为空"},
widget=widgets.TextInput(attrs={"class": "form-control"}))
email = forms.EmailField(label="邮箱", error_messages={"required": "该字段不能为空", "invalid": "格式错误"},
widget=widgets.TextInput(attrs={"class": "form-control"}))
tel = forms.CharField(label="手机号", widget=widgets.TextInput(attrs={"class": "form-control"})) def clean_name(self):    # 局部钩子
val = self.cleaned_data.get("name")
ret = UserInfo.objects.filter(name=val)
if not ret:
return val
else:
raise ValidationError("该用户已注册!") def clean_tel(self):    # 局部钩子
val = self.cleaned_data.get("tel")
if len(val) == 11:
return val
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('两次密码不一致')
else:
return self.cleaned_data
无论是form  post 还是ajax 都需要携带 csrf token
AJAX请求如何设置csrf_token
方式一
"csrfmiddlewaretoken": $("[name = 'csrfmiddlewaretoken']").val() // 使用JQuery取出csrfmiddlewaretoken的值,拼接到data中 方式二
需要引入一个jquery.cookie.js插件
headers: {"X-CSRFToken": $.cookie('csrftoken')}, // 从Cookie取csrf_token,并设置ajax请求头

一般用:

// 从cooikie 取 csft token 的值
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken'); // 将csrftoken 设置到ajax 请求头中,后续的ajax请求就会自动携带这个csrf token
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
} $.ajaxSetup({
beforeSend: function (xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
<script src="/static/jquery-3.2.1.min.js"></script>
<script src="/static/init_ajax.js"></script>

publish=forms.ModelChoiceField(queryset=Publish.objects.all())
单选
publish=forms.ModelMultChoiceField(queryset=Publish.objects.all())
多选
<select name="a" id="id_a">
<option value="1">a</option>
<option value="2" selected="">b</option>
</select>
-------------------------------------------------------------
<select name="b" id="id_b">
<option value="1">a</option>
<option value="2" selected="">b</option>
</select>
------------------------------------------------------------
<ul id="id_c">
<li><label for="id_c_0"><input type="radio" name="c" value="1" required="" id="id_c_0">
a</label>
</li>
<li><label for="id_c_1"><input type="radio" name="c" value="2" checked="" required="" id="id_c_1">
b</label>
</li>
</ul>
------------------------------------------------------------
<select name="d" required="" id="id_d" multiple="multiple">
<option value="1" selected="">a</option>
<option value="2" selected="">b</option>
</select>
------------------------------------------------------------------
<input type="checkbox" name="e" value="(1, 2)" checked="" required="" id="id_e">
-------------------------------------------------------------
<ul id="id_f">
<li><label for="id_f_0"><input type="checkbox" name="f" value="1" checked="" id="id_f_0">
a</label>
</li>
<li><label for="id_f_1"><input type="checkbox" name="f" value="2" checked="" id="id_f_1">
b</label>
</li>
</ul>

 choices实时从数据库中更新

方式一
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['f'].widget.choices = Book.objects.all().values_list('id', 'caption')
for field in iter(self.fields):
self.fields[field].widget.attrs.update({
'class': 'form-control'
})
方式二 在字段定义时直接使用ORM语句

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:12 DurationField(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, # 查询数据库中的数据
empty_label="---------", # 默认空显示内容
to_field_name=None, # HTML中value的值对应的字段
limit_choices_to=None # ModelForm中对queryset二次筛选 ModelMultipleChoiceField(ModelChoiceField)
... django.forms.models.ModelMultipleChoiceField TypedChoiceField(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类型

自定义验证规则

from django.core.validators import RegexValidatorfields.CharField(validators=[RegexValidator(r'^159[0-9]+$', '数字必须以159开头'),])
from django.core.exceptions import ValidationError
CharField(validators=[mobile_validate, ]) def mobile_validate(value):
mobile_re = re.compile(r'^(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$')
if not mobile_re.match(value):
raise ValidationError('手机号码格式错误')
def clean_username(self):
username = self.cleaned_data.get('username')
if '' in username:
raise ValidationError('只含666学不会')
else:
return username

最新文章

  1. python获取ip代理列表爬虫
  2. scala + intellij idea 环境搭建及编译、打包
  3. VS20xx IDE开发应用时_拷贝VS环境的库文件DLL到目标设备上运行的操作步骤
  4. Android 中Service生命周期
  5. C Shell 中的特殊变量
  6. Nhibernate的log4net和系统的log4net使用技巧
  7. asp.net 框架初接触
  8. javaee学习-Cookie使用范例
  9. linux下安装redis并自启动
  10. C++关于编译器合成的默认构造函数
  11. linux apache模块的安装
  12. js计算时间差,包括计算,天,时,分,秒
  13. 前端性能监控系统 &amp; 前端数据分析系统
  14. php curl使用 常用操作
  15. 潭州课堂25班:Ph201805201 django 项目 第三十课 linux 系统迁移 (课堂笔记)
  16. Unity 2D相机公式换算(从其他博客上抄的)
  17. Spring Cloud config之二:功能介绍
  18. python标准库介绍——3 stat 模块详解
  19. [洛谷P1709] [USACO5.5]隐藏口令Hidden Password
  20. FastReport.Net使用:[16]图片控件使用

热门文章

  1. 如何用Nginx解决前端跨域问题?
  2. 【Python 06】汇率兑换1.0-1(IPO与字符串转数字)
  3. 初识服务发现及Consul框架的简单使用
  4. 在Mac OS X下使用Apache、PHP、MySQL、Netbeans、Yii
  5. iview 动态渲染menu时active-name无效的问题
  6. jenkins集成python时出现&quot;Non-ASCII character &#39;\xe6&#39; in file&quot;错误解决方法
  7. js-模块化(三大模块化规范)
  8. Linux--虚拟环境
  9. SPP-net原理解读
  10. How to proof MD5