Código fonte para django.forms.forms

"""Form classes"""importcopyfromcollectionsimportOrderedDictfromdjango.core.exceptionsimportNON_FIELD_ERRORS,ValidationError# BoundField is imported for backwards compatibility in Django 1.9fromdjango.forms.boundfieldimportBoundField# NOQAfromdjango.forms.fieldsimportField,FileField# pretty_name is imported for backwards compatibility in Django 1.9fromdjango.forms.utilsimportErrorDict,ErrorList,pretty_name# NOQAfromdjango.forms.widgetsimportMedia,MediaDefiningClassfromdjango.utils.functionalimportcached_propertyfromdjango.utils.htmlimportconditional_escape,html_safefromdjango.utils.safestringimportmark_safefromdjango.utils.translationimportgettextas_from.renderersimportget_default_renderer__all__=('BaseForm','Form')classDeclarativeFieldsMetaclass(MediaDefiningClass):"""Collect Fields declared on the base classes."""def__new__(mcs,name,bases,attrs):# Collect fields from current class.current_fields=[]forkey,valueinlist(attrs.items()):ifisinstance(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()forbaseinreversed(new_class.__mro__):# Collect fields from base class.ifhasattr(base,'declared_fields'):declared_fields.update(base.declared_fields)# Field shadowing.forattr,valueinbase.__dict__.items():ifvalueisNoneandattrindeclared_fields:declared_fields.pop(attr)new_class.base_fields=declared_fieldsnew_class.declared_fields=declared_fieldsreturnnew_class@classmethoddef__prepare__(metacls,name,bases,**kwds):# Remember the order in which form fields are defined.returnOrderedDict()@html_safeclassBaseForm:""" 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=Nonefield_order=Noneprefix=Noneuse_required_attribute=Truedef__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=dataisnotNoneorfilesisnotNoneself.data={}ifdataisNoneelsedataself.files={}iffilesisNoneelsefilesself.auto_id=auto_idifprefixisnotNone:self.prefix=prefixself.initial=initialor{}self.error_class=error_class# Translators: This is the default suffix added to form field labelsself.label_suffix=label_suffixiflabel_suffixisnotNoneelse_(':')self.empty_permitted=empty_permittedself._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_orderiffield_orderisNoneelsefield_order)ifuse_required_attributeisnotNone: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.ifrendererisNone:ifself.default_rendererisNone:renderer=get_default_renderer()else:renderer=self.default_rendererifisinstance(self.default_renderer,type):renderer=renderer()self.renderer=rendererdeforder_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. """iffield_orderisNone:returnfields=OrderedDict()forkeyinfield_order:try:fields[key]=self.fields.pop(key)exceptKeyError:# ignore unknown fieldspassfields.update(self.fields)# add remaining fields in original orderself.fields=fieldsdef__str__(self):returnself.as_table()def__repr__(self):ifself._errorsisNone:is_valid="Unknown"else:is_valid=self.is_boundandnotbool(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):fornameinself.fields:yieldself[name]def__getitem__(self,name):"""Return a BoundField with the given name."""try:field=self.fields[name]exceptKeyError:raiseKeyError("Key '%s' not found in '%s'. Choices are: %s."%(name,self.__class__.__name__,', '.join(sorted(fforfinself.fields)),))ifnamenotinself._bound_fields_cache:self._bound_fields_cache[name]=field.get_bound_field(self,name)returnself._bound_fields_cache[name]@propertydeferrors(self):"""Return an ErrorDict for the data provided for the form."""ifself._errorsisNone:self.full_clean()returnself._errorsdefis_valid(self):"""Return True if the form has no errors, or False otherwise."""returnself.is_boundandnotself.errorsdefadd_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)ifself.prefixelsefield_namedefadd_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=[],[]forname,fieldinself.fields.items():html_class_attr=''bf=self[name]# Escape and cache in local variable.bf_errors=self.error_class([conditional_escape(error)forerrorinbf.errors])ifbf.is_hidden:ifbf_errors:top_errors.extend([_('(Hidden field %(name)s) %(error)s')%{'name':name,'error':str(e)}foreinbf_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()ifcss_classes:html_class_attr=' class="%s"'%css_classesiferrors_on_separate_rowandbf_errors:output.append(error_row%str(bf_errors))ifbf.label:label=conditional_escape(bf.label)label=bf.label_tag(label)or''else:label=''iffield.help_text:help_text=help_text_html%field.help_textelse: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,})iftop_errors:output.insert(0,error_row%top_errors)ifhidden_fields:# Insert any hidden fields in the last row.str_hidden=''.join(hidden_fields)ifoutput:last_row=output[-1]# Chop off the trailing row_ender (e.g. '</td></tr>') and# insert the hidden fields.ifnotlast_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_enderelse:# If there aren't any rows in the output, just append the# hidden fields.output.append(str_hidden)returnmark_safe('\n'.join(output))defas_table(self):"Return this form rendered as HTML <tr>s -- excluding the <table></table>."returnself._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)defas_ul(self):"Return this form rendered as HTML <li>s -- excluding the <ul></ul>."returnself._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)defas_p(self):"Return this form rendered as HTML <p>s."returnself._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)defnon_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. """returnself.errors.get(NON_FIELD_ERRORS,self.error_class(error_class='nonfield'))defadd_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. """ifnotisinstance(error,ValidationError):# Normalize to ValidationError and let its constructor# do the hard work of making sense of the input.error=ValidationError(error)ifhasattr(error,'error_dict'):iffieldisnotNone:raiseTypeError("The argument `field` must be `None` when the `error` ""argument contains errors for multiple fields.")else:error=error.error_dictelse:error={fieldorNON_FIELD_ERRORS:error.error_list}forfield,error_listinerror.items():iffieldnotinself.errors:iffield!=NON_FIELD_ERRORSandfieldnotinself.fields:raiseValueError("'%s' has no field named '%s'."%(self.__class__.__name__,field))iffield==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)iffieldinself.cleaned_data:delself.cleaned_data[field]defhas_error(self,field,code=None):ifcodeisNone:returnfieldinself.errorsiffieldinself.errors:forerrorinself.errors.as_data()[field]:iferror.code==code:returnTruereturnFalsedeffull_clean(self):""" Clean all of self.data and populate self._errors and self.cleaned_data. """self._errors=ErrorDict()ifnotself.is_bound:# Stop further processing.returnself.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.ifself.empty_permittedandnotself.has_changed():returnself._clean_fields()self._clean_form()self._post_clean()def_clean_fields(self):forname,fieldinself.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.iffield.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:ifisinstance(field,FileField):initial=self.get_initial_for_field(field,name)value=field.clean(value,initial)else:value=field.clean(value)self.cleaned_data[name]=valueifhasattr(self,'clean_%s'%name):value=getattr(self,'clean_%s'%name)()self.cleaned_data[name]=valueexceptValidationErrorase:self.add_error(name,e)def_clean_form(self):try:cleaned_data=self.clean()exceptValidationErrorase:self.add_error(None,e)else:ifcleaned_dataisnotNone:self.cleaned_data=cleaned_datadef_post_clean(self):""" An internal hook for performing additional cleaning after form cleaning is complete. Used for model validation in model forms. """passdefclean(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__'. """returnself.cleaned_datadefhas_changed(self):"""Return True if data differs from initial."""returnbool(self.changed_data)@cached_propertydefchanged_data(self):data=[]forname,fieldinself.fields.items():prefixed_name=self.add_prefix(name)data_value=field.widget.value_from_datadict(self.data,self.files,prefixed_name)ifnotfield.show_hidden_initial:# Use the BoundField's initial as this is the value passed to# the widget.initial_value=self[name].initialelse: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))exceptValidationError:# Always assume data has changed if validation fails.data.append(name)continueiffield.has_changed(initial_value,data_value):data.append(name)returndata@propertydefmedia(self):"""Return all media required to render the widgets on this form."""media=Media()forfieldinself.fields.values():media=media+field.widget.mediareturnmediadefis_multipart(self):""" Return True if the form needs to be multipart-encoded, i.e. it has FileInput, or False otherwise. """forfieldinself.fields.values():iffield.widget.needs_multipart_form:returnTruereturnFalsedefhidden_fields(self):""" Return a list of all the BoundField objects that are hidden fields. Useful for manual form layout in templates. """return[fieldforfieldinselfiffield.is_hidden]defvisible_fields(self):""" Return a list of BoundField objects that aren't hidden fields. The opposite of the hidden_fields() method. """return[fieldforfieldinselfifnotfield.is_hidden]defget_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)ifcallable(value):value=value()returnvalue

"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.