3
(h=M                 @   s  d Z ddlmZ ddlZddlmZ ddlmZmZ ddl	m
Z
 ddlmZmZ ddlmZmZmZ dd	lmZmZ dd
lmZ ddlmZmZ ddlmZ ddlmZmZ ddlm Z  ddl!m"Z# dZ$G dd deZ%eeG dd de&Z'G dd dej(e%e'Z)dS )z
Form classes
    )unicode_literalsN)OrderedDict)NON_FIELD_ERRORSValidationError)
BoundField)Field	FileField)	ErrorDict	ErrorListpretty_name)MediaMediaDefiningClass)six)
force_textpython_2_unicode_compatible)cached_property)conditional_escape	html_safe)	mark_safe)ugettextBaseFormFormc                   s    e Zd ZdZ fddZ  ZS )DeclarativeFieldsMetaclasszF
    Metaclass that collects Fields declared on the base classes.
    c                s   g }x:t |j D ]*\}}t|tr|j||f |j| qW |jdd d t||d< tt	| j
| |||}t }xZt|jD ]L}	t|	dr|j|	j x0|	jj D ]"\}
}|d kr|
|kr|j|
 qW qW ||_||_|S )Nc             S   s
   | d j S )N   )Zcreation_counter)x r   6/tmp/pip-install-q3hcpn_q/Django/django/forms/forms.py<lambda>&   s    z4DeclarativeFieldsMetaclass.__new__.<locals>.<lambda>)keydeclared_fields)listitems
isinstancer   appendpopsortr   superr   __new__reversed__mro__hasattrupdater   __dict__base_fields)ZmcsnamebasesattrsZcurrent_fieldsr   value	new_classr   baseattr)	__class__r   r   r'      s$    

z"DeclarativeFieldsMetaclass.__new__)__name__
__module____qualname____doc__r'   __classcell__r   r   )r5   r   r      s   r   c            
   @   s  e Zd ZdZdZdZdddddeddddf
ddZdd Zd	d
 Z	dd Z
dd Zdd Zedd Zdd Zdd Zdd Zdd Zdd Zdd Zdd  Zd!d" Zd#d$ Zd=d%d&Zd'd( Zd)d* Zd+d, Zd-d. Zd/d0 Zd1d2 Zed3d4 Z ed5d6 Z!d7d8 Z"d9d: Z#d;d< Z$dS )>r   NTzid_%sFc             C   s   |d k	p|d k	| _ |pi | _|p"i | _|| _|d k	r:|| _|p@i | _|| _|d k	rV|ntd| _|| _	d | _
tj| j| _i | _| j|	d kr| jn|	 |
d k	r|
| _d S )N:)is_bounddatafilesauto_idprefixinitialerror_class_label_suffixempty_permitted_errorscopydeepcopyr-   fields_bound_fields_cacheorder_fieldsfield_orderuse_required_attribute)selfr=   r>   r?   r@   rA   rB   rD   rE   rL   rM   r   r   r   __init__H   s     


zBaseForm.__init__c             C   s`   |dkrdS t  }x6|D ].}y| jj|||< W q tk
rD   Y qX qW |j| j || _dS )a  
        Rearranges the fields according to field_order.

        field_order is a list of field names specifying the order. Fields not
        included in the list are appended in the default order for backward
        compatibility with subclasses not overriding field_order. If field_order
        is None, all fields are kept in the order defined in the class.
        Unknown fields in field_order are ignored to allow disabling fields in
        form subclasses without redefining ordering.
        N)r   rI   r$   KeyErrorr+   )rN   rL   rI   r   r   r   r   rK   d   s    

zBaseForm.order_fieldsc             C   s   | j  S )N)as_table)rN   r   r   r   __str__z   s    zBaseForm.__str__c             C   sB   | j d krd}n| jo t| j  }d| jj| j|dj| jd S )NUnknownz?<%(cls)s bound=%(bound)s, valid=%(valid)s, fields=(%(fields)s)>;)clsZboundZvalidrI   )rF   r<   boolr5   r6   joinrI   )rN   is_validr   r   r   __repr__}   s    
zBaseForm.__repr__c             c   s   x| j D ]}| | V  qW d S )N)rI   )rN   r.   r   r   r   __iter__   s    zBaseForm.__iter__c             C   sv   y| j | }W n@ tk
rN   td|| jjdjtdd | j D f Y nX || jkrl|j| || j|< | j| S )z)Returns a BoundField with the given name.z,Key '%s' not found in '%s'. Choices are: %s.z, c             s   s   | ]
}|V  qd S )Nr   ).0fr   r   r   	<genexpr>   s    z'BaseForm.__getitem__.<locals>.<genexpr>)rI   rP   r5   r6   rW   sortedrJ   Zget_bound_field)rN   r.   fieldr   r   r   __getitem__   s    &
zBaseForm.__getitem__c             C   s   | j dkr| j  | j S )z7Returns an ErrorDict for the data provided for the formN)rF   
full_clean)rN   r   r   r   errors   s    
zBaseForm.errorsc             C   s   | j o| j S )z
        Returns True if the form has no errors. Otherwise, False. If errors are
        being ignored, returns False.
        )r<   rb   )rN   r   r   r   rX      s    zBaseForm.is_validc             C   s   | j rd| j |f S |S )z
        Returns the field name with a prefix appended, if this Form has a
        prefix set.

        Subclasses may wish to override.
        z%s-%s)r@   )rN   
field_namer   r   r   
add_prefix   s    zBaseForm.add_prefixc             C   s   d| j | S )zL
        Add a 'initial' prefix for checking dynamic initial values
        z
initial-%s)rd   )rN   rc   r   r   r   add_initial_prefix   s    zBaseForm.add_initial_prefixc                s  | j  }g g  }}x
| jj D ]\ }	d}
|   }| jdd |jD }|jr~|rl|j fdd|D  |jtj	| q |j
 }|rd| }
|r|r|j|t|  |jrtt|j}|j|pd}nd}|	jr|t|	j }nd}|j|t|t|tj	|||
||jd  q W |r:|jd|t|  |rdj|}|r|d }|j|s|dddd|
ddd }|j| |d	t|  | | |d< n
|j| td
j|S )zIHelper function for outputting HTML. Used by as_table(), as_ul(), as_p(). c             S   s   g | ]}t |qS r   )r   )r[   errorr   r   r   
<listcomp>   s    z)BaseForm._html_output.<locals>.<listcomp>c                s"   g | ]}t d  t|d qS )z!(Hidden field %(name)s) %(error)s)r.   rg   )rC   r   )r[   e)r.   r   r   rh      s   z class="%s")rb   labelr_   	help_texthtml_class_attrcss_classesrc   r   r   N
ro   )non_field_errorsrI   r!   rB   rb   	is_hiddenextendr#   r   	text_typerm   r   rj   r   Z	label_tagrk   Z	html_nameinsertrW   endswithlenr   )rN   
normal_row	error_row	row_enderhelp_text_htmlerrors_on_separate_rowZ
top_errorsoutputhidden_fieldsr_   rl   ZbfZ	bf_errorsrm   rj   rk   Z
str_hiddenZlast_rowr   )r.   r   _html_output   sf    





 
zBaseForm._html_outputc             C   s   | j ddddddS )zJReturns this form rendered as HTML <tr>s -- excluding the <table></table>.zW<tr%(html_class_attr)s><th>%(label)s</th><td>%(errors)s%(field)s%(help_text)s</td></tr>z <tr><td colspan="2">%s</td></tr>z
</td></tr>z&<br /><span class="helptext">%s</span>F)rw   rx   ry   rz   r{   )r~   )rN   r   r   r   rQ     s    zBaseForm.as_tablec             C   s   | j ddddddS )zDReturns this form rendered as HTML <li>s -- excluding the <ul></ul>.zF<li%(html_class_attr)s>%(errors)s%(label)s %(field)s%(help_text)s</li>z<li>%s</li>z</li>z! <span class="helptext">%s</span>F)rw   rx   ry   rz   r{   )r~   )rN   r   r   r   as_ul  s    zBaseForm.as_ulc             C   s   | j ddddddS )z(Returns this form rendered as HTML <p>s.z:<p%(html_class_attr)s>%(label)s %(field)s%(help_text)s</p>z%sz</p>z! <span class="helptext">%s</span>T)rw   rx   ry   rz   r{   )r~   )rN   r   r   r   as_p  s    zBaseForm.as_pc             C   s   | j jt| jddS )z
        Returns an ErrorList of errors that aren't associated with a particular
        field -- i.e., from Form.clean(). Returns an empty ErrorList if there
        are none.
        nonfield)rB   )rb   getr   rB   )rN   r   r   r   rp   #  s    zBaseForm.non_field_errorsc             C   s   t |tst|}t|dr6|dk	r.tdqD|j}n|p<t|ji}x|j D ]\}}|| jkr|tkr|| j	krt
d| jj|f |tkr| jdd| j|< n| j | j|< | j| j| || jkrN| j|= qNW dS )a^  
        Update the content of `self._errors`.

        The `field` argument is the name of the field to which the errors
        should be added. If its value is None the errors will be treated 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. What we define as
        an "error" can be either a simple string or an instance of
        ValidationError with its message attribute set and what we define as
        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.
        
error_dictNzbThe argument `field` must be `None` when the `error` argument contains errors for multiple fields.z'%s' has no field named '%s'.r   )rB   )r"   r   r*   	TypeErrorr   r   
error_listr!   rb   rI   
ValueErrorr5   r6   rB   rF   rr   cleaned_data)rN   r_   rg   r   r   r   r   	add_error+  s&    



zBaseForm.add_errorc             C   sF   |d kr|| j kS || j krBx$| j j | D ]}|j|kr,dS q,W dS )NTF)rb   Zas_datacode)rN   r_   r   rg   r   r   r   	has_error[  s    


zBaseForm.has_errorc             C   sH   t  | _| jsdS i | _| jr,| j  r,dS | j  | j  | j  dS )zc
        Cleans all of self.data and populates self._errors and
        self.cleaned_data.
        N)	r	   rF   r<   r   rE   has_changed_clean_fields_clean_form_post_clean)rN   r   r   r   ra   d  s    zBaseForm.full_cleanc             C   s   x| j j D ]\}}|jr,| jj||j}n|jj| j| j| j	|}yht
|trp| jj||j}|j||}n
|j|}|| j|< t| d| rt| d|  }|| j|< W q tk
r } z| j|| W Y d d }~X qX qW d S )Nzclean_%s)rI   r!   disabledrA   r   widgetvalue_from_datadictr=   r>   rd   r"   r   cleanr   r*   getattrr   r   )rN   r.   r_   r1   rA   ri   r   r   r   r   v  s    


zBaseForm._clean_fieldsc             C   sN   y| j  }W n. tk
r: } z| jd | W Y d d }~X nX |d k	rJ|| _d S )N)r   r   r   r   )rN   r   ri   r   r   r   r     s    zBaseForm._clean_formc             C   s   dS )z
        An internal hook for performing additional cleaning after form cleaning
        is complete. Used for model validation in model forms.
        Nr   )rN   r   r   r   r     s    zBaseForm._post_cleanc             C   s   | j S )a+  
        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__'.
        )r   )rN   r   r   r   r     s    zBaseForm.cleanc             C   s
   t | jS )z<
        Returns True if data differs from initial.
        )rV   changed_data)rN   r   r   r   r     s    zBaseForm.has_changedc       	      C   s   g }x| j j D ]\}}| j|}|jj| j| j|}|js\| jj	||j}t
|r| }nP| j|}|j }y|j|j| j| j|}W n  tk
r   |j| wY nX |j||r|j| qW |S )N)rI   r!   rd   r   r   r=   r>   Zshow_hidden_initialrA   r   callablere   hidden_widgetZ	to_pythonr   r#   r   )	rN   r=   r.   r_   Zprefixed_nameZ
data_valueinitial_valueZinitial_prefixed_namer   r   r   r   r     s&    


zBaseForm.changed_datac             C   s*   t  }x| jj D ]}||jj }qW |S )z`
        Provide a description of all media required to render the widgets on this form
        )r   rI   valuesr   media)rN   r   r_   r   r   r   r     s    zBaseForm.mediac             C   s$   x| j j D ]}|jjrdS qW dS )zz
        Returns True if the form needs to be multipart-encoded, i.e. it has
        FileInput. Otherwise, False.
        TF)rI   r   r   Zneeds_multipart_form)rN   r_   r   r   r   is_multipart  s    zBaseForm.is_multipartc             C   s   dd | D S )z
        Returns a list of all the BoundField objects that are hidden fields.
        Useful for manual form layout in templates.
        c             S   s   g | ]}|j r|qS r   )rq   )r[   r_   r   r   r   rh     s    z*BaseForm.hidden_fields.<locals>.<listcomp>r   )rN   r   r   r   r}     s    zBaseForm.hidden_fieldsc             C   s   dd | D S )z
        Returns a list of BoundField objects that aren't hidden fields.
        The opposite of the hidden_fields() method.
        c             S   s   g | ]}|j s|qS r   )rq   )r[   r_   r   r   r   rh     s    z+BaseForm.visible_fields.<locals>.<listcomp>r   )rN   r   r   r   visible_fields  s    zBaseForm.visible_fields)N)%r6   r7   r8   rL   r@   rM   r
   rO   rK   rR   rY   rZ   r`   propertyrb   rX   rd   re   r~   rQ   r   r   rp   r   r   ra   r   r   r   r   r   r   r   r   r   r}   r   r   r   r   r   r   =   sB   	N			0
			

c               @   s   e Zd ZdZdS )r   z3A collection of Fields, plus their associated data.N)r6   r7   r8   r9   r   r   r   r   r     s   )r   r   )*r9   
__future__r   rG   collectionsr   Zdjango.core.exceptionsr   r   Zdjango.forms.boundfieldr   Zdjango.forms.fieldsr   r   Zdjango.forms.utilsr	   r
   r   Zdjango.forms.widgetsr   r   Zdjango.utilsr   Zdjango.utils.encodingr   r   Zdjango.utils.functionalr   Zdjango.utils.htmlr   r   Zdjango.utils.safestringr   Zdjango.utils.translationr   rC   __all__r   objectr   with_metaclassr   r   r   r   r   <module>   s.   "
   *