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')
方法二:直接在类中定义全局变量
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()) # 单选
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.
补充:
<!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>