Django框架详细介绍---Form表单
一、概述
在HTML页面中,利用form表单向后端提交数据时,需要编写input等输入标签并用form标签包裹起来,与此同时,在很多应用场景之下需要对用户输入的数据校验,例如注册登录页面中,校验用户注册时输入的用户名是否合法或者该用户是否被注册等并弹出相应的提示信息
Django内的form组件就是为了实现这些功能:
1)生成HTML标签
2)对提交的数据进行校验
3)当数据校验等情况下保存上次输入的内容
在生产场景,前后端都应该进行数据校验
二、应用
1.常用字段与插件
在APP中新建的forms.py文件中,字段用于对数据的校验,插件用于自动生成HTML标签
1)initial,设置input中的初始值
error_messages,对当前字段不符合指定的规则时,重写错误信息
password,指定input输入框的输入类型
password = forms.CharField(
label="密码",
# initial 设置初始值
# initial="123456",
# 字段规则,约束条件
min_length=6,
max_length=64,
# 重写错误信息
error_messages={
"required": "密码不能为空",
"min_length": "密码至少6个字符",
"max_length": "密码最多64个字符",
},
# PasswordInput 密码类型
widget=forms.widgets.PasswordInput(
attrs={"class": "form-control"}
)
)
2)单选Select
hobby = forms.fields.ChoiceField(
choices=((1, "篮球"), (2, "足球"), (3, "跑步"),),
label="爱好",
initial=3,
widget=forms.widgets.Select
)
3)多选Select
hobby = forms.fields.MultipleChoiceField(
choices=((1, "篮球"), (2, "足球"), (3, "跑步"), ),
label="爱好",
initial=[1, 3],
widget=forms.widgets.SelectMultiple
)
4)单选Checkbox
keep = forms.fields.ChoiceField(
label="是否记住密码",
initial="checked",
widget=forms.widgets.CheckboxInput
)
5)多选Checkbox
hobby = forms.fields.MultipleChoiceField(
choices=((1, "篮球"), (2, "足球"), (3, "跑步"),),
label="爱好",
initial=[1, 3],
widget=forms.widgets.CheckboxSelectMultiple
)
补充:
在使用选择标签时,需要注意choices的选项可以从数据库中获取,但由于是经验字段,获取的值无法实时更新,可通过自定义构造方法,在拉取表单之前将数据库中的数据拉取到自动以的表单内
方法一:在form类中的init中
from django.forms import Form
from django.forms import widgets
from django.forms import fields class MyForm(Form): user = fields.ChoiceField(
# choices=((1, '上海'), (2, '北京'),),
initial=2,
widget=widgets.Select
) def __init__(self, *args, **kwargs):
super(MyForm,self).__init__(*args, **kwargs)
# self.fields['user'].choices = ((1, '上海'), (2, '北京'),)
# 或
self.fields['user'].choices = models.Classes.objects.all().values_list('id','caption')
在form类中init中添加
方法二:直接在类中定义全局变量
from django import forms
from django.forms import fields
from django.forms import models as form_model class FInfo(forms.Form):
authors = form_model.ModelMultipleChoiceField(queryset=models.NNewType.objects.all()) # 多选
# authors = form_model.ModelChoiceField(queryset=models.NNewType.objects.all()) # 单选
直接在form类中定义全局变量
2.Django Form所有内置字段
Field
required=True, 是否允许为空
widget=None, HTML插件
label=None, 用于生成Label标签或显示内容
initial=None, 初始值
help_text='', 帮助信息(在标签旁边显示)
error_messages=None, 错误信息 {'required': '不能为空', 'invalid': '格式错误'}
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 import forms
from django.core.exceptions import ValidationError
from django.core.validators import RegexValidator
from BBS import models class LoginForm(forms.Form):
'''
自定义登录表单
'''
username = forms.CharField(
label="用户名",
min_length=2,
max_length=12,
error_messages={
"required": "用户名不能为空",
"min_length": "用户名至少2个字符",
"max_length": "用户名最多12个字符",
},
widget=forms.widgets.TextInput(
attrs={"class": "form-control"}
)
) password = forms.CharField(
label="密码",
min_length=6,
max_length=64,
error_messages={
"required": "密码不能为空",
"min_length": "密码至少6个字符",
"max_length": "密码最多64个字符",
},
# PasswordInput 密码类型
widget=forms.widgets.PasswordInput(
attrs={"class": "form-control"}
)
) class RegForm(forms.Form):
'''
自定义注册表单
'''
username = forms.CharField(
label="用户名",
min_length=2,
max_length=12,
error_messages={
"required": "用户名不能为空",
"min_length": "用户名至少2个字符",
"max_length": "用户名最多12个字符",
},
widget=forms.widgets.TextInput(
attrs={"class": "form-control"}
)
) password = forms.CharField(
label="密码",
min_length=6,
max_length=64,
error_messages={
"required": "密码不能为空",
"min_length": "密码至少6个字符",
"max_length": "密码最多64个字符",
},
widget=forms.widgets.PasswordInput(
attrs={"class": "form-control"}
)
) re_password = forms.CharField(
label="确认密码",
min_length=6,
max_length=64,
error_messages={
"required": "确认密码不能为空",
"min_length": "密码至少6个字符",
"max_length": "密码最多64个字符",
},
widget=forms.widgets.PasswordInput(
attrs={"class": "form-control"}
)
) phone = forms.CharField(
label="手机号码",
min_length=11,
max_length=11,
validators=[
RegexValidator(r'^\d{11}$', "手机号必须十一位,且必须是数字"),
RegexValidator(r'^1[356789][0-9]{9}$', "手机号格式不对"),
],
error_messages={
"required": "手机号不能为空",
"min_length": "手机号码必须11位",
"max_length": "手机号码必须11位",
},
widget=forms.widgets.TextInput(
attrs={"class": "form-control"}
)
) # 局部钩子
def clean_username(self):
username = self.cleaned_data.get("username", "")
arlt_list = ["反共", "牛逼", "操你", "滚你"]
for i in arlt_list:
if i in username:
raise ValidationError("用户名中存在敏感字符")
elif models.UserInfo.objects.filter(username=username):
raise ValidationError("用户名已存在")
else:
return username # 全局钩子
def clean(self):
password = self.cleaned_data.get("password", "")
re_password = self.cleaned_data.get("re_password", "") if re_password and password == re_password:
return self.cleaned_data
else:
err_msg = "两次输入的密码不一致"
self.add_error("re_password", err_msg)
raise ValidationError(err_msg)
自定义注册登录表单
通过自定义表单中的钩子函数解读forms中的部分源码
def _clean_fields(self):
for name, field in self.fields.items():
# value_from_datadict() gets the data from the data dictionaries.
# Each widget type knows how to retrieve its own data, because some
# widgets split data over several HTML fields.
'''
对自定义表单中,根据每个自定义的字段中的规则进行校验
1. 校验通过则执行 self.cleaned_data[name] = value
2. 校验失败则执行 self.add_error(name, e)
'''
if field.disabled:
value = self.get_initial_for_field(field, name)
else:
value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
try:
if isinstance(field, FileField):
initial = self.get_initial_for_field(field, name)
value = field.clean(value, initial)
else:
value = field.clean(value)
self.cleaned_data[name] = value if hasattr(self, 'clean_%s' % name):
value = getattr(self, 'clean_%s' % name)()
self.cleaned_data[name] = value except ValidationError as e:
self.add_error(name, e)
if hasattr(self, 'clean_%s' % name):
value = getattr(self, 'clean_%s' % name)()
self.cleaned_data[name] = value
以上源代码中,利用hasattr方法通过反射,针对自定义表单中的某个字段设置自定义校验
高级用法:
1)通过form类中的init方法给字段批量添加样式
class LoginForm(forms.Form): ... def __init__(self, *args, **kwargs):
super(LoginForm, self).__init__(*args, **kwargs)
for field in iter(self.fields):
self.fields[field].widget.attrs.update({
'class': 'form-control'
})
2)注册页面中应用Bootstrap样式以及通过AJAX实现文件上传
附录:
form类全部源码
"""
Form classes
""" import copy
from collections import OrderedDict from django.core.exceptions import NON_FIELD_ERRORS, ValidationError
# BoundField is imported for backwards compatibility in Django 1.9
from django.forms.boundfield import BoundField # NOQA
from django.forms.fields import Field, FileField
# pretty_name is imported for backwards compatibility in Django 1.9
from django.forms.utils import ErrorDict, ErrorList, pretty_name # NOQA
from django.forms.widgets import Media, MediaDefiningClass
from django.utils.functional import cached_property
from django.utils.html import conditional_escape, html_safe
from django.utils.safestring import mark_safe
from django.utils.translation import gettext as _ from .renderers import get_default_renderer __all__ = ('BaseForm', 'Form') class DeclarativeFieldsMetaclass(MediaDefiningClass):
"""Collect Fields declared on the base classes."""
def __new__(mcs, name, bases, attrs):
# Collect fields from current class.
current_fields = []
for key, value in list(attrs.items()):
if isinstance(value, Field):
current_fields.append((key, value))
attrs.pop(key)
attrs['declared_fields'] = OrderedDict(current_fields) new_class = super(DeclarativeFieldsMetaclass, mcs).__new__(mcs, name, bases, attrs) # Walk through the MRO.
declared_fields = OrderedDict()
for base in reversed(new_class.__mro__):
# Collect fields from base class.
if hasattr(base, 'declared_fields'):
declared_fields.update(base.declared_fields) # Field shadowing.
for attr, value in base.__dict__.items():
if value is None and attr in declared_fields:
declared_fields.pop(attr) new_class.base_fields = declared_fields
new_class.declared_fields = declared_fields return new_class @classmethod
def __prepare__(metacls, name, bases, **kwds):
# Remember the order in which form fields are defined.
return OrderedDict() @html_safe
class BaseForm:
"""
The main implementation of all the Form logic. Note that this class is
different than Form. See the comments by the Form class for more info. Any
improvements to the form API should be made to this class, not to the Form
class.
"""
default_renderer = None
field_order = None
prefix = None
use_required_attribute = True def __init__(self, data=None, files=None, auto_id='id_%s', prefix=None,
initial=None, error_class=ErrorList, label_suffix=None,
empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None):
self.is_bound = data is not None or files is not None
self.data = {} if data is None else data
self.files = {} if files is None else files
self.auto_id = auto_id
if prefix is not None:
self.prefix = prefix
self.initial = initial or {}
self.error_class = error_class
# Translators: This is the default suffix added to form field labels
self.label_suffix = label_suffix if label_suffix is not None else _(':')
self.empty_permitted = empty_permitted
self._errors = None # Stores the errors after clean() has been called. # The base_fields class attribute is the *class-wide* definition of
# fields. Because a particular *instance* of the class might want to
# alter self.fields, we create self.fields here by copying base_fields.
# Instances should always modify self.fields; they should not modify
# self.base_fields.
self.fields = copy.deepcopy(self.base_fields)
self._bound_fields_cache = {}
self.order_fields(self.field_order if field_order is None else field_order) if use_required_attribute is not None:
self.use_required_attribute = use_required_attribute # Initialize form renderer. Use a global default if not specified
# either as an argument or as self.default_renderer.
if renderer is None:
if self.default_renderer is None:
renderer = get_default_renderer()
else:
renderer = self.default_renderer
if isinstance(self.default_renderer, type):
renderer = renderer()
self.renderer = renderer def order_fields(self, field_order):
"""
Rearrange the fields according to field_order. field_order is a list of field names specifying the order. Append fields
not included in the list in the default order for backward compatibility
with subclasses not overriding field_order. If field_order is None,
keep all fields in the order defined in the class. Ignore unknown
fields in field_order to allow disabling fields in form subclasses
without redefining ordering.
"""
if field_order is None:
return
fields = OrderedDict()
for key in field_order:
try:
fields[key] = self.fields.pop(key)
except KeyError: # ignore unknown fields
pass
fields.update(self.fields) # add remaining fields in original order
self.fields = fields def __str__(self):
return self.as_table() def __repr__(self):
if self._errors is None:
is_valid = "Unknown"
else:
is_valid = self.is_bound and not bool(self._errors)
return '<%(cls)s bound=%(bound)s, valid=%(valid)s, fields=(%(fields)s)>' % {
'cls': self.__class__.__name__,
'bound': self.is_bound,
'valid': is_valid,
'fields': ';'.join(self.fields),
} def __iter__(self):
for name in self.fields:
yield self[name] def __getitem__(self, name):
"""Return a BoundField with the given name."""
try:
field = self.fields[name]
except KeyError:
raise KeyError(
"Key '%s' not found in '%s'. Choices are: %s." % (
name,
self.__class__.__name__,
', '.join(sorted(f for f in self.fields)),
)
)
if name not in self._bound_fields_cache:
self._bound_fields_cache[name] = field.get_bound_field(self, name)
return self._bound_fields_cache[name] @property
def errors(self):
"""Return an ErrorDict for the data provided for the form."""
if self._errors is None:
self.full_clean()
return self._errors def is_valid(self):
"""Return True if the form has no errors, or False otherwise."""
return self.is_bound and not self.errors def add_prefix(self, field_name):
"""
Return the field name with a prefix appended, if this Form has a
prefix set. Subclasses may wish to override.
"""
return '%s-%s' % (self.prefix, field_name) if self.prefix else field_name def add_initial_prefix(self, field_name):
"""Add a 'initial' prefix for checking dynamic initial values."""
return 'initial-%s' % self.add_prefix(field_name) def _html_output(self, normal_row, error_row, row_ender, help_text_html, errors_on_separate_row):
"Output HTML. Used by as_table(), as_ul(), as_p()."
top_errors = self.non_field_errors() # Errors that should be displayed above all fields.
output, hidden_fields = [], [] for name, field in self.fields.items():
html_class_attr = ''
bf = self[name]
# Escape and cache in local variable.
bf_errors = self.error_class([conditional_escape(error) for error in bf.errors])
if bf.is_hidden:
if bf_errors:
top_errors.extend(
[_('(Hidden field %(name)s) %(error)s') % {'name': name, 'error': str(e)}
for e in bf_errors])
hidden_fields.append(str(bf))
else:
# Create a 'class="..."' attribute if the row should have any
# CSS classes applied.
css_classes = bf.css_classes()
if css_classes:
html_class_attr = ' class="%s"' % css_classes if errors_on_separate_row and bf_errors:
output.append(error_row % str(bf_errors)) if bf.label:
label = conditional_escape(bf.label)
label = bf.label_tag(label) or ''
else:
label = '' if field.help_text:
help_text = help_text_html % field.help_text
else:
help_text = '' output.append(normal_row % {
'errors': bf_errors,
'label': label,
'field': bf,
'help_text': help_text,
'html_class_attr': html_class_attr,
'css_classes': css_classes,
'field_name': bf.html_name,
}) if top_errors:
output.insert(0, error_row % top_errors) if hidden_fields: # Insert any hidden fields in the last row.
str_hidden = ''.join(hidden_fields)
if output:
last_row = output[-1]
# Chop off the trailing row_ender (e.g. '</td></tr>') and
# insert the hidden fields.
if not last_row.endswith(row_ender):
# This can happen in the as_p() case (and possibly others
# that users write): if there are only top errors, we may
# not be able to conscript the last row for our purposes,
# so insert a new, empty row.
last_row = (normal_row % {
'errors': '',
'label': '',
'field': '',
'help_text': '',
'html_class_attr': html_class_attr,
'css_classes': '',
'field_name': '',
})
output.append(last_row)
output[-1] = last_row[:-len(row_ender)] + str_hidden + row_ender
else:
# If there aren't any rows in the output, just append the
# hidden fields.
output.append(str_hidden)
return mark_safe('\n'.join(output)) def as_table(self):
"Return this form rendered as HTML <tr>s -- excluding the <table></table>."
return self._html_output(
normal_row='<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>',
error_row='<tr><td colspan="2">%s</td></tr>',
row_ender='</td></tr>',
help_text_html='<br /><span class="helptext">%s</span>',
errors_on_separate_row=False) def as_ul(self):
"Return this form rendered as HTML <li>s -- excluding the <ul></ul>."
return self._html_output(
normal_row='<li%(html_class_attr)s>%(errors)s%(label)s %(field)s%(help_text)s</li>',
error_row='<li>%s</li>',
row_ender='</li>',
help_text_html=' <span class="helptext">%s</span>',
errors_on_separate_row=False) def as_p(self):
"Return this form rendered as HTML <p>s."
return self._html_output(
normal_row='<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>',
error_row='%s',
row_ender='</p>',
help_text_html=' <span class="helptext">%s</span>',
errors_on_separate_row=True) def non_field_errors(self):
"""
Return an ErrorList of errors that aren't associated with a particular
field -- i.e., from Form.clean(). Return an empty ErrorList if there
are none.
"""
return self.errors.get(NON_FIELD_ERRORS, self.error_class(error_class='nonfield')) def add_error(self, field, error):
"""
Update the content of `self._errors`. The `field` argument is the name of the field to which the errors
should be added. If it's None, treat the errors as NON_FIELD_ERRORS. The `error` argument can be a single error, a list of errors, or a
dictionary that maps field names to lists of errors. An "error" can be
either a simple string or an instance of ValidationError with its
message attribute set and a "list or dictionary" can be an actual
`list` or `dict` or an instance of ValidationError with its
`error_list` or `error_dict` attribute set. If `error` is a dictionary, the `field` argument *must* be None and
errors will be added to the fields that correspond to the keys of the
dictionary.
"""
if not isinstance(error, ValidationError):
# Normalize to ValidationError and let its constructor
# do the hard work of making sense of the input.
error = ValidationError(error) if hasattr(error, 'error_dict'):
if field is not None:
raise TypeError(
"The argument `field` must be `None` when the `error` "
"argument contains errors for multiple fields."
)
else:
error = error.error_dict
else:
error = {field or NON_FIELD_ERRORS: error.error_list} for field, error_list in error.items():
if field not in self.errors:
if field != NON_FIELD_ERRORS and field not in self.fields:
raise ValueError(
"'%s' has no field named '%s'." % (self.__class__.__name__, field))
if field == NON_FIELD_ERRORS:
self._errors[field] = self.error_class(error_class='nonfield')
else:
self._errors[field] = self.error_class()
self._errors[field].extend(error_list)
if field in self.cleaned_data:
del self.cleaned_data[field] def has_error(self, field, code=None):
if code is None:
return field in self.errors
if field in self.errors:
for error in self.errors.as_data()[field]:
if error.code == code:
return True
return False def full_clean(self):
"""
Clean all of self.data and populate self._errors and self.cleaned_data.
"""
self._errors = ErrorDict()
if not self.is_bound: # Stop further processing.
return
self.cleaned_data = {}
# If the form is permitted to be empty, and none of the form data has
# changed from the initial data, short circuit any validation.
if self.empty_permitted and not self.has_changed():
return self._clean_fields()
self._clean_form()
self._post_clean() def _clean_fields(self):
for name, field in self.fields.items():
# value_from_datadict() gets the data from the data dictionaries.
# Each widget type knows how to retrieve its own data, because some
# widgets split data over several HTML fields.
if field.disabled:
value = self.get_initial_for_field(field, name)
else:
value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name))
try:
if isinstance(field, FileField):
initial = self.get_initial_for_field(field, name)
value = field.clean(value, initial)
else:
value = field.clean(value)
self.cleaned_data[name] = value
if hasattr(self, 'clean_%s' % name):
value = getattr(self, 'clean_%s' % name)()
self.cleaned_data[name] = value
except ValidationError as e:
self.add_error(name, e) def _clean_form(self):
try:
cleaned_data = self.clean()
except ValidationError as e:
self.add_error(None, e)
else:
if cleaned_data is not None:
self.cleaned_data = cleaned_data def _post_clean(self):
"""
An internal hook for performing additional cleaning after form cleaning
is complete. Used for model validation in model forms.
"""
pass def clean(self):
"""
Hook for doing any extra form-wide cleaning after Field.clean() has been
called on every field. Any ValidationError raised by this method will
not be associated with a particular field; it will have a special-case
association with the field named '__all__'.
"""
return self.cleaned_data def has_changed(self):
"""Return True if data differs from initial."""
return bool(self.changed_data) @cached_property
def changed_data(self):
data = []
for name, field in self.fields.items():
prefixed_name = self.add_prefix(name)
data_value = field.widget.value_from_datadict(self.data, self.files, prefixed_name)
if not field.show_hidden_initial:
# Use the BoundField's initial as this is the value passed to
# the widget.
initial_value = self[name].initial
else:
initial_prefixed_name = self.add_initial_prefix(name)
hidden_widget = field.hidden_widget()
try:
initial_value = field.to_python(hidden_widget.value_from_datadict(
self.data, self.files, initial_prefixed_name))
except ValidationError:
# Always assume data has changed if validation fails.
data.append(name)
continue
if field.has_changed(initial_value, data_value):
data.append(name)
return data @property
def media(self):
"""Return all media required to render the widgets on this form."""
media = Media()
for field in self.fields.values():
media = media + field.widget.media
return media def is_multipart(self):
"""
Return True if the form needs to be multipart-encoded, i.e. it has
FileInput, or False otherwise.
"""
for field in self.fields.values():
if field.widget.needs_multipart_form:
return True
return False def hidden_fields(self):
"""
Return a list of all the BoundField objects that are hidden fields.
Useful for manual form layout in templates.
"""
return [field for field in self if field.is_hidden] def visible_fields(self):
"""
Return a list of BoundField objects that aren't hidden fields.
The opposite of the hidden_fields() method.
"""
return [field for field in self if not field.is_hidden] def get_initial_for_field(self, field, field_name):
"""
Return initial data for field on form. Use initial data from the form
or the field, in that order. Evaluate callable values.
"""
value = self.initial.get(field_name, field.initial)
if callable(value):
value = value()
return value class Form(BaseForm, metaclass=DeclarativeFieldsMetaclass):
"A collection of Fields, plus their associated data."
# This is a separate class from BaseForm in order to abstract the way
# self.fields is specified. This class (Form) is the one that does the
# fancy metaclass stuff purely for the semantic sugar -- it allows one
# to define a form using declarative syntax.
# BaseForm itself has no way of designating self.fields.
forms源码
补充:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/static/bootstrap-3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="/static/font-awesome-4.7.0/css/font-awesome.min.css">
<title>用户注册</title> <style>
.reg-form {
margin-top: 70px;
}
#show-avatar {
width: 90px;
height: 90px;
}
</style> </head>
<body> <div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3 reg-form">
<form class="form-horizontal" autocomplete="off" novalidate>
{% csrf_token %}
<div class="form-group">
<label for="{{ form_obj.username.id_for_label }}"
class="col-sm-2 control-label">{{ form_obj.username.label }}</label>
<div class="col-sm-10">
{{ form_obj.username }}
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label for="{{ form_obj.password.id_for_label }}"
class="col-sm-2 control-label">{{ form_obj.password.label }}</label>
<div class="col-sm-10">
{{ form_obj.password }}
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label for="{{ form_obj.re_password.id_for_label }}"
class="col-sm-2 control-label">{{ form_obj.re_password.label }}</label>
<div class="col-sm-10">
{{ form_obj.re_password }}
<span class="help-block"></span>
</div>
</div>
<div class="form-group">
<label for="{{ form_obj.phone.id_for_label }}"
class="col-sm-2 control-label">{{ form_obj.phone.label }}</label>
<div class="col-sm-10">
{{ form_obj.phone }}
<span class="help-block"></span>
</div>
</div> <div class="form-group">
<label class="col-sm-2 control-label">头像</label>
<div class="col-sm-10">
<input accept="image/*" type="file" id="id_avatar" name="avatar" style="display: none">
<label for="id_avatar">
<img src="/static/img/default.png" id="show-avatar">
</label>
</div>
</div> <div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" id="reg-button">注册</button>
</div>
</div>
</form>
</div>
</div>
</div> <script src="/static/jquery-3.3.1.js"></script>
<script src="/static/bootstrap-3.3.7/js/bootstrap.min.js"></script>
<script src="/static/setupAjax.js"></script> <script>
// 找到注册按钮绑定点击事件
$("#reg-button").click(function () {
var dataObj = new FormData();
dataObj.append("username", $("#id_username").val());
dataObj.append("password", $("#id_password").val());
dataObj.append("re_password", $("#id_re_password").val());
dataObj.append("phone", $("#id_phone").val());
// 获取上传头像的对象
dataObj.append("avatar", $("#id_avatar")[0].files[0]); console.log($("#id_avatar")[0].files[0]);
$.ajax({
url: "/register/",
type: "POST",
//
processData: false,
//
contentType: false,
data: dataObj,
success: function (data) {
console.log(data);
if (data.code) {
// 存在报错信息,则页面的相应位置展示
var errMsgObj = data.data;
$.each(errMsgObj, function (k, v) {
// k: 字段名
// v:报错信息的数组
// 根据字段名找对应的input标签,将错误信息添加到相应的标签内
$("#id_" + k).next(".help-block").text(v[0]).parent().parent().addClass("has-error");
})
} else {
console.log(data.data);
location.href = data.data || "/login/"
} }
})
}); // 给每一个input标签绑定focus事件,移除当前的错误提示信息
$("input.form-control").focus(function () {
$(this).next(".help-block").text("").parent().parent().removeClass("has-error");
}); // 头像预览
$("#id_avatar").change(function () {
// 找到你选中的那个头像文件
var fileObj = this.files[0];
console.log(fileObj);
// 读取文件路径
var fileReader = new FileReader();
fileReader.readAsDataURL(fileObj);
// 等图片被读取完毕之后,再做后续操作
fileReader.onload = function () {
// 设置预览图片
$("#show-avatar").attr("src", fileReader.result);
};
}); </script> </body>
</html>
添加Bootstarp样式和AJAX实现文件上传
Django框架详细介绍---Form表单的更多相关文章
- Django框架获取各种form表单数据
Django中获取text,password 名字:<input type="text" name="name"><br><br& ...
- Django基础,Day5 - form表单投票详解
投票URL polls/urls.py: # ex: /polls/5/vote/ url(r'^(?P<question_id>[0-9]+)/vote/$', views.vote, ...
- Django框架详细介绍---请求流程
Django请求流程图 1.客户端发送请求 2.wsgiref是Django封装的套接字,它将客户端发送过来的请求(请求头.请求体封装成request) 1)解析请求数据 2)封装响应数据 3.中间件 ...
- Django框架详细介绍---模板系统
Django模板系统 官方文档: https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#std:templatetag-for 1 ...
- Django学习系列之Form表单结合ajax
Forms结合ajax Forms的验证流程: 定义用户输入规则的类,字段的值必须等于html中name属性的值(pwd= forms.CharField(required=True)=<i ...
- 用layui前端框架弹出form表单以及提交
第一步:引用两个文件 第二步:点击删除按钮弹出提示框 /*删除开始*/ $(".del").click(function () { var id = $(this).attr(&q ...
- Django框架详细介绍---Admin后台管理
1.Admin组件使用 Django内集成了web管理工具,Django在启动过程中会执行setting.py文件,初始化Django内置组件.注册APP.添加环境变量等 # Application ...
- Django框架详细介绍---视图系统
Django视图系统 1.什么是视图 在Django中,一个视图函数/类,称为视图.实质就是一个用户自定义的简单函数,用来接收WEB请求并xing响应请求,响应的内容可以是一个HTML文件.重定向.一 ...
- web前端框架之自定义form表单验证
自定义form验证初试 .在后端创建一个类MainForm,并且在类中自定义host ip port phone等,然后写入方法,在post方法中创建MainForm对象,并且把post方法中的sel ...
随机推荐
- cmd应用基础 扫盲教程
cmd是什么? 对于程序员而言,cmd命令提示符是windows操作系统下一个比较重要的工具.对于程序员而言,为了追求更高的效率而抛弃花俏的界面已然是意见很常见的行为,截止到目前的,全世界仍有大量的服 ...
- LOJ #6303. 水题 (约数 质因数)
#6303. 水题 内存限制 10 MiB 时间限制:1000 ms 标准输入输出 题目描述 给定正整数 n,kn, kn,k,已知非负整数 xxx 满足 n!modkx=0,求 xmaxx_{max ...
- C# ToString()和Convert.ToString()的区别【转】
一.一般用法说明 ToString()是Object的扩展方法,所以都有ToString()方法;而Convert.ToString(param)(其中param参数的数据类型可以是各种基本数据类型, ...
- vue2.0无限滚动加载数据插件
做vue项目用到下拉滚动加载数据功能,由于选的UI库(element)没有这个组件,就用Vue-infinite-loading 这个插件代替,使用中遇到的一些问题及使用方法,总结作记录! 安装: ...
- Go语言基础之time包
Go语言基础之time包 时间和日期是我们编程中经常会用到的,本文主要介绍了Go语言内置的time包的基本用法. Go语言中导入包 Go语言中使用import关键字导入包,包的名字使用双引号(”)包裹 ...
- jquery运用FormData结合Ajax异步上传表单,超实用
首先创建一个formData,其中参数,就是你的form表单,jquery要加0,也可以用document.querySelector("form")得到 var formData ...
- .NET平台常用的框架
转自:https://www.cnblogs.com/lhxsoft/p/8609089.html 分布式缓存框架: Microsoft Velocity:微软自家分布式缓存服务框架. Memcahe ...
- react路由
针对多个列表导航公用一个组建,然后 有两种路由方式 1.import {HashRouter as Router,Route,Link} from 'react-router-dom' 不过这个路由中 ...
- 删除U8中单据已经审核完成但工作流未完成的任务
问题描述: U8工作流终审结点后面还有节点时,当终审终点完成后,系统会通知后面的节点进行审核,但单据显示已经审核完成,后面的节点无法审核,工作任务会一直挂着,无法删除. 例如下图中,节点"终 ...
- Jenkins调度Selenium脚本不能打开浏览器解决办法
前提:在Myeclipse里面可以启动起来浏览器,在Jenkins中不能启动浏览器 原因:以程序的方式安装了jenkins,jenkins就成了windows的一个服务了,默认是设置为自动启动的如下图 ...