3
(h                 @   s,  d Z ddlmZ ddlmZ ddlmZ ddlmZm	Z	m
Z
mZ ddlmZmZ ddlmZmZ ddlmZmZ dd	lmZ dd
lmZmZmZ ddlmZ ddlmZmZ ddl m!Z!m"Z" ddl#m$Z$m%Z& d:Z'dZ(d;ddZ)d<ddZ*d=d dZ+G d!d" d"e,Z-G d#d$ d$eZ.G d%d deZ/G d&d dej0e.e/Z1e1dddddddddf
d'dZ2G d(d deZ3e1de3d)d*d*ddddd*dddddd*dfd+dZ4G d,d de3Z5d>d-d.Z6e1e5dddd/d*d0dddd*dddddd*dfd1dZ7G d2d3 d3eZ8G d4d5 d5e,Z9G d6d deZ:G d7d de:Z;d8d9 Z<dS )?z[
Helper functions for creating Form classes from Django models
and database field objects.
    )unicode_literals)OrderedDict)chain)NON_FIELD_ERRORS
FieldErrorImproperlyConfiguredValidationError)ChoiceFieldField)BaseFormDeclarativeFieldsMetaclass)BaseFormSetformset_factory)	ErrorList)HiddenInputMultipleHiddenInputSelectMultiple)six)
force_text
smart_text)capfirstget_text_list)ugettextugettext_lazy	ModelFormBaseModelFormmodel_to_dictfields_for_modelModelChoiceFieldModelMultipleChoiceField
ALL_FIELDSBaseModelFormSetmodelformset_factoryBaseInlineFormSetinlineformset_factorymodelform_factory__all__Nc       	      C   s   ddl m} |j}| j}g }x|jD ]}|j s$t||js$|j|krHq$|dk	r\|j|kr\q$|rl|j|krlq$|j	 r| |j j
jj| j| j| j|jrq$t||jr|j| q$|j|||j  q$W x|D ]}|j|||j  qW |S )z
    Constructs and returns a model instance from the bound ``form``'s
    ``cleaned_data``, but does not save the returned instance to the
    database.
    r   )modelsN)Z	django.dbr'   _metacleaned_datafieldseditable
isinstance	AutoFieldnamehas_defaultfieldwidgetZvalue_omitted_from_datadatafiles
add_prefixZ	FileFieldappendsave_form_data)	forminstancer*   excluder'   optsr)   Zfile_field_listf r<   7/tmp/pip-install-q3hcpn_q/Django/django/forms/models.pyconstruct_instance$   s*    
$
r>   c             C   sh   | j }i }xXt|j|j|jD ]B}t|dds0q|r@|j|kr@q|rP|j|krPq|j| ||j< qW |S )a  
    Returns a dict containing the data in ``instance`` suitable for passing as
    a Form's ``initial`` keyword argument.

    ``fields`` is an optional list of field names. If provided, only the named
    fields will be included in the returned dict.

    ``exclude`` is an optional list of field names. If provided, the named
    fields will be excluded from the returned dict, even if they are listed in
    the ``fields`` argument.
    r+   F)r(   r   concrete_fieldsprivate_fieldsmany_to_manygetattrr.   Zvalue_from_object)r8   r*   r9   r:   r2   r;   r<   r<   r=   r   K   s    c
                s   g }
g | j }ddlm   fdd|jD }xtt|j||jD ]}t|dds|dk	rF|j	|krFdks||j	krFt
d|j	| jf qF|dk	r|j	|krqFr|j	krqFi }|r|j	|kr||j	 |d	< |tks|r|j	|krd
|d< |r|j	|kr||j	 |d< |r4|j	|kr4||j	 |d< |rT|j	|krT||j	 |d< |	rt|j	|	krt|	|j	 |d< |dkr|jf |}n t|stdn||f|}|r|
j|j	|f qFj|j	 qFW t|
|rtfdd|D S )a  
    Returns a ``OrderedDict`` containing form fields for the given model.

    ``fields`` is an optional list of field names. If provided, only the named
    fields will be included in the returned fields.

    ``exclude`` is an optional list of field names. If provided, the named
    fields will be excluded from the returned fields, even if they are listed
    in the ``fields`` argument.

    ``widgets`` is a dictionary of model field names mapped to a widget.

    ``formfield_callback`` is a callable that takes a model field and returns
    a form field.

    ``localized_fields`` is a list of names of fields which should be localized.

    ``labels`` is a dictionary of model field names mapped to a label.

    ``help_texts`` is a dictionary of model field names mapped to a help text.

    ``error_messages`` is a dictionary of model field names mapped to a
    dictionary of error messages.

    ``field_classes`` is a dictionary of model field names mapped to a form
    field class.
    r   )r
   c                s   g | ]}t | r|qS r<   )r,   ).0r;   )
ModelFieldr<   r=   
<listcomp>   s    z$fields_for_model.<locals>.<listcomp>r+   FNzH'%s' cannot be specified for %s model form as it is a non-editable fieldr1   TZlocalizelabel	help_texterror_messages
form_classz1formfield_callback must be a function or callablec                s4   g | ],}  s r| kr|kr|j |fqS r<   )get)rC   r;   )r9   
field_dictignoredr<   r=   rE      s    )r(   Zdjango.db.models.fieldsr
   r@   sortedr   r?   rA   rB   r.   r   __name__r    	formfieldcallable	TypeErrorr5   r   )modelr*   r9   widgetsformfield_callbacklocalized_fieldslabels
help_textsrH   field_classesZ
field_listr:   Zsortable_private_fieldsr;   kwargsrO   r<   )rD   r9   rK   rL   r=   r   d   sV    


c               @   s   e Zd ZdddZdS )ModelFormOptionsNc             C   s   t |dd | _t |dd | _t |dd | _t |dd | _t |dd | _t |dd | _t |dd | _t |dd | _t |d	d | _	d S )
NrR   r*   r9   rS   rU   rV   rW   rH   rX   )
rB   rR   r*   r9   rS   rU   rV   rW   rH   rX   )selfoptionsr<   r<   r=   __init__   s    zModelFormOptions.__init__)N)rN   
__module____qualname__r]   r<   r<   r<   r=   rZ      s   rZ   c                   s   e Zd Z fddZ  ZS )ModelFormMetaclassc                s  d }x,|D ]$}t |dr
t |jdr
|jj}P q
W |jd|}tt| j| |||}|tfkrb|S tt	|dd  }|_
xDdD ]<}	t	||	}
t|
tjr~|
tkr~d|j|	|
d }t|q~W |jr|jd kr|jd krtd| |jtkrd |_t|j|j|j|j||j|j|j|j|j
}d	d
 tj|D }t|t|jj  }|rtd}|dj ||jjf }t!||j"|j n|j}||_#|S )NMetarT   r*   r9   rU   zP%(model)s.Meta.%(opt)s cannot be a string. Did you mean to type: ('%(value)s',)?)rR   optvaluez|Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form %s needs updating.c             S   s   g | ]\}}|s|qS r<   r<   )rC   kvr<   r<   r=   rE      s    z.ModelFormMetaclass.__new__.<locals>.<listcomp>z&Unknown field(s) (%s) specified for %sz, )r*   r9   rU   )$hasattrra   rT   popsuperr`   __new__r   rZ   rB   r(   r,   r   string_typesr    rN   rQ   rR   r*   r9   r   r   rS   rU   rV   rW   rH   rX   	iteritemssetZdeclared_fieldskeysjoinr   updateZbase_fields)Zmcsr.   basesattrsZbase_formfield_callbackbrT   	new_classr:   rb   rc   msgr*   Znone_model_fieldsZmissing_fieldsmessage)	__class__r<   r=   ri      sT    






zModelFormMetaclass.__new__)rN   r^   r_   ri   __classcell__r<   r<   )rv   r=   r`      s   r`   c            
       sr   e Zd Zdddddeddddf
 f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e_  ZS )r   Nzid_%sFc                s   | j }|jd krtd|	d kr0|j | _i }n|	| _t|	|j|j}|d k	rX|j| d| _t	t
| j|||||||||
d	 xJ| jD ]@}| j| }t|drt|dr|j }|d k	r|jj||_qW d S )Nz'ModelForm has no model class specified.F)use_required_attributequerysetget_limit_choices_to)r(   rR   
ValueErrorr8   r   r*   r9   ro   _validate_uniquerh   r   r]   rf   rz   ry   Zcomplex_filter)r[   r2   r3   auto_idprefixinitialerror_classZlabel_suffixZempty_permittedr8   rx   r:   Zobject_data
field_namerO   limit_choices_to)rv   r<   r=   r]     s(    




zBaseModelForm.__init__c             C   s   g }x| j jjD ]}|j}|| jkr2|j|j q| jjrT|| jjkrT|j|j q| jjrv|| jjkrv|j|j q|| jj kr|j|j q| j| }| jj	|}|j
 r|j r||jkr|j|j qW |S )z
        For backwards-compatibility, several types of fields need to be
        excluded from model validation. See the following tickets for
        details: #12507, #12521, #12553
        )r8   r(   r*   r.   r5   r9   _errorsrm   r)   rJ   Zblankrequiredempty_values)r[   r9   r;   r0   Z
form_fieldZfield_valuer<   r<   r=   _get_validation_exclusions.  s     
	
z(BaseModelForm._get_validation_exclusionsc             C   s   d| _ | jS )NT)r|   r)   )r[   r<   r<   r=   cleanX  s    zBaseModelForm.cleanc             C   s   | j }t|dr|j}nt|i}x|j D ]t\}}|tkrV|jrVt|jkrV|jt }n|| jkr*| j| j}nq*x,|D ]$}t|trv|j	|krv||j	 |_
qvW q*W | jd | d S )N
error_dict)r(   rf   r   r   itemsrH   r*   r,   r   coderu   Z	add_error)r[   errorsr:   r   r0   messagesrH   ru   r<   r<   r=   _update_errors\  s     





zBaseModelForm._update_errorsc             C   s   | j }| j }x*| jj D ]\}}t|tr|j| qW yt| | j|j|j	| _W n, t
k
r } z| j| W Y d d }~X nX y| jj|dd W n, t
k
r } z| j| W Y d d }~X nX | jr| j  d S )NF)r9   validate_unique)r(   r   r*   r   r,   InlineForeignKeyFieldr5   r>   r8   r9   r   r   Z
full_cleanr|   r   )r[   r:   r9   r.   r0   er<   r<   r=   _post_cleanx  s    	
zBaseModelForm._post_cleanc             C   sL   | j  }y| jj|d W n, tk
rF } z| j| W Y dd}~X nX dS )z
        Calls the instance's validate_unique() method and updates the form's
        validation errors if any were raised.
        )r9   N)r   r8   r   r   r   )r[   r9   r   r<   r<   r=   r     s
    zBaseModelForm.validate_uniquec             C   s   | j }| jj}| jj}| jj}x`t|j|jD ]N}t|ds>q.|rN|j	|krNq.|r^|j	|kr^q.|j	|kr.|j
| j||j	  q.W dS )zS
        Save the many-to-many fields and generic relations for this form.
        r6   N)r)   r(   r9   r*   r8   r   rA   r@   rf   r.   r6   )r[   r)   r9   r*   r:   r;   r<   r<   r=   	_save_m2m  s    

zBaseModelForm._save_m2mTc             C   sP   | j r*td| jjj| jjjr dndf |rB| jj  | j  n| j| _	| jS )z
        Save this form's self.instance object if commit=True. Otherwise, add
        a save_m2m() method to the form which can be called after the instance
        is saved manually at a later time. Return the model instance.
        z8The %s could not be %s because the data didn't validate.createdchanged)
r   r{   r8   r(   Zobject_name_stateaddingsaver   save_m2m)r[   commitr<   r<   r=   r     s    

zBaseModelForm.save)T)rN   r^   r_   r   r]   r   r   r   r   r   r   r   alters_datarw   r<   r<   )rv   r=   r     s   *
c               @   s   e Zd ZdS )r   N)rN   r^   r_   r<   r<   r<   r=   r     s   c             C   s  d| i}|dk	r||d< |dk	r(||d< |dk	r8||d< |dk	rH||d< |dk	rX||d< |dk	rh||d< |	dk	rx|	|d	< |
dk	r|
|d
< t f}t|dr|jt f}ttd||}|rt||_| jtd }||d}t|dddkot|dddkrt	dt|||f|S )a  
    Returns a ModelForm containing form fields for the given model.

    ``fields`` is an optional list of field names. If provided, only the named
    fields will be included in the returned fields. If omitted or '__all__',
    all fields will be used.

    ``exclude`` is an optional list of field names. If provided, the named
    fields will be excluded from the returned fields, even if they are listed
    in the ``fields`` argument.

    ``widgets`` is a dictionary of model field names mapped to a widget.

    ``localized_fields`` is a list of names of fields which should be localized.

    ``formfield_callback`` is a callable that takes a model field and returns
    a form field.

    ``labels`` is a dictionary of model field names mapped to a label.

    ``help_texts`` is a dictionary of model field names mapped to a help text.

    ``error_messages`` is a dictionary of model field names mapped to a
    dictionary of error messages.

    ``field_classes`` is a dictionary of model field names mapped to a form
    field class.
    rR   Nr*   r9   rS   rU   rV   rW   rH   rX   ra   ZForm)ra   rT   zZCalling modelform_factory without defining 'fields' or 'exclude' explicitly is prohibited.)
objectrf   ra   typestrstaticmethodrT   rN   rB   r   )rR   r7   r*   r9   rT   rS   rU   rV   rW   rH   rX   rq   parentra   
class_nameZform_class_attrsr<   r<   r=   r%     s>    %


c                   s   e Zd ZdZdZe Zd) fdd	Z fddZdd	 Z	d
d Z
 fddZdd Zd*ddZd+ddZd,ddZd-ddZde_dd Zdd Zdd Zdd  Zd!d" Zd.d#d$Zd/d%d&Z fd'd(Z  ZS )0r!   zO
    A ``FormSet`` for editing a queryset and/or adding new objects to it.
    Nid_%sc                sB   || _ |jdd | _||||d}|j| tt| jf | d S )Nr   )r2   r3   r}   r~   )ry   rg   initial_extraro   rh   r!   r]   )r[   r2   r3   r}   r~   ry   rY   defaults)rv   r<   r=   r]   2  s
    
zBaseModelFormSet.__init__c                s&   | j p
| jst| j S tt| j S )z>Returns the number of forms that are required in this FormSet.)r2   r3   lenget_querysetrh   r!   initial_form_count)r[   )rv   r<   r=   r   :  s    z#BaseModelFormSet.initial_form_countc             C   s*   t | dsdd | j D | _| jj|S )N_object_dictc             S   s   i | ]}||j qS r<   )pk)rC   or<   r<   r=   
<dictcomp>B  s    z5BaseModelFormSet._existing_object.<locals>.<dictcomp>)rf   r   r   rJ   )r[   r   r<   r<   r=   _existing_object@  s    
z!BaseModelFormSet._existing_objectc             C   s    x|j dk	r|j j }qW |jS )z
        If the field is a related field, fetch the concrete field's (that
        is, the ultimate pointed-to field's) to_python.
        N)remote_fieldZget_related_field	to_python)r[   r0   r<   r<   r=   _get_to_pythonE  s    zBaseModelFormSet._get_to_pythonc                s   | j r`|| j k r`d| j|| jjjjf }| j| }| jjj}| j|}||}| j	||d< || j k rd|kr| j
 | |d< || j kr| jry| j|| j   |d< W n tk
r   Y nX tt| j|f|S )Nz%s-%sr8   r   )is_boundr   r4   rR   r(   r   r.   r2   r   r   r   r   
IndexErrorrh   r!   _construct_form)r[   irY   Zpk_keyr   pk_fieldr   )rv   r<   r=   r   N  s    


z BaseModelFormSet._construct_formc             C   sL   t | dsF| jd k	r| j}n| jjj }|js@|j| jjjj	}|| _
| j
S )N	_queryset)rf   ry   rR   _default_managerr   orderedZorder_byr(   r   r.   r   )r[   qsr<   r<   r=   r   `  s    

zBaseModelFormSet.get_querysetTc             C   s   |j |dS )z:Saves and returns a new model instance for the given form.)r   )r   )r[   r7   r   r<   r<   r=   save_news  s    zBaseModelFormSet.save_newc             C   s   |j |dS )z@Saves and returns an existing model instance for the given form.)r   )r   )r[   r7   r8   r   r<   r<   r=   save_existingw  s    zBaseModelFormSet.save_existingc             C   s   |r|j   dS )z#Deletes an existing model instance.N)delete)r[   objr   r<   r<   r=   delete_existing{  s    z BaseModelFormSet.delete_existingc                s0   |sg  _  fdd}| _ j| j| S )zSaves model instances for every form, adding and changing instances
        as necessary, and returns the list of instances.
        c                 s   x j D ]} | j  qW d S )N)saved_formsr   )r7   )r[   r<   r=   r     s    z'BaseModelFormSet.save.<locals>.save_m2m)r   r   save_existing_objectssave_new_objects)r[   r   r   r<   )r[   r=   r     s
    zBaseModelFormSet.savec             C   s   | j   d S )N)r   )r[   r<   r<   r=   r     s    zBaseModelFormSet.cleanc                s  t  }t  }jfddjD }xB|D ]:  j } jj|d\}}|jt |}|jt |}q,W g }x|D ]\}}	t  }
x|D ]  fdd|	D }tdd |D }|od |kr||
kr|jj	|	 j
j g jt< x|	D ]}| jkr j|= qW |
j| qW qtW x|D ]}t  }
|\}}}}x|D ]  jrB j| d k	rB j| d k	rB|dkr j| }|j|j|jf}nt j| |f} j| f| }||
kr|jj| j
j g jt<  j|= |
j| qBW q&W |rt|d S )Nc                s    g | ]}|j  r| kr|qS r<   )Zis_valid)rC   r7   )forms_to_deleter<   r=   rE     s    z4BaseModelFormSet.validate_unique.<locals>.<listcomp>)r9   c             3   s0   | ](}| j kr|jkr|n j | V  qd S )N)r)   unique_fields)rC   r0   )r7   r[   r<   r=   	<genexpr>  s   z3BaseModelFormSet.validate_unique.<locals>.<genexpr>c             s   s$   | ]}t |d r|j n|V  qdS )_get_pk_valN)rf   r   )rC   dr<   r<   r=   r     s   date)rl   deleted_formsZformsr   r8   Z_get_unique_checksuniontupler5   get_unique_error_messager   get_form_errorr   r   r)   addyearmonthdayrB   get_date_error_messager   )r[   Zall_unique_checksZall_date_checksZvalid_formsr9   Zunique_checksZdate_checksr   Zuclassunique_checkZ	seen_dataZrow_datar0   
date_checklookupZ
unique_forr   Z	date_datar2   r<   )r7   r   r[   r=   r     sV    










z BaseModelFormSet.validate_uniquec             C   sD   t |dkr tdd|d i S tddt|tjtdi S d S )N   z0Please correct the duplicate data for %(field)s.r0   r   zFPlease correct the duplicate data for %(field)s, which must be unique.and)r   r   r   r   	text_type_)r[   r   r<   r<   r=   r     s
    z)BaseModelFormSet.get_unique_error_messagec             C   s&   t d|d |d tj|d d S )NzoPlease correct the duplicate data for %(field_name)s which must be unique for the %(lookup)s in %(date_field)s.      r   )r   Z
date_fieldr   )r   r   r   )r[   r   r<   r<   r=   r     s
    z'BaseModelFormSet.get_date_error_messagec             C   s   t dS )Nz*Please correct the duplicate values below.)r   )r[   r<   r<   r=   r     s    zBaseModelFormSet.get_form_errorc             C   s   g | _ g | _| jsg S g }| j}x| jD ]z}|j}||krb|jd krFq(| jj| | j||d q(|j r(| j j||j	f |j| j
|||d |s(| jj| q(W |S )N)r   )Zchanged_objectsZdeleted_objectsZinitial_formsr   r8   r   r5   r   has_changedZchanged_datar   r   )r[   r   Zsaved_instancesr   r7   r   r<   r<   r=   r     s&    
z&BaseModelFormSet.save_existing_objectsc             C   s^   g | _ xP| jD ]F}|j sq| jr.| j|r.q| j j| j||d |s| jj| qW | j S )N)r   )Znew_objectsZextra_formsr   
can_deleteZ_should_delete_formr5   r   r   )r[   r   r7   r<   r<   r=   r     s    z!BaseModelFormSet.save_new_objectsc       	         s2  ddl m m}m} | jjj | _} fdd|sH|j|j	kr|j
rf|jjjr\dn|jj}n:y |dk	r| j | j}nd}W n tk
r   d}Y nX t||st||r|jjjj }n| jjj }|j|jjj}|jjr|jjj| jjt}nt}t||d|d|j	| jj< tt| j|| dS )z0Add a hidden field for the object's primary key.r   )r-   OneToOneField
ForeignKeyc                s6   | j  p4| jp4t|  p4| jo4| jjo4| jjjjS )N)r+   Zauto_createdr,   r   Zparent_linkrR   r(   r   )r   )r-   pk_is_not_editabler<   r=   r     s    z7BaseModelFormSet.add_fields.<locals>.pk_is_not_editableNF)r   r   r1   )django.db.modelsr-   r   r   rR   r(   r   	_pk_fieldr.   r*   r   r8   r   r   r   r   r,   r   r   ZusingdbrS   rJ   r   r   rh   r!   
add_fields)	r[   r7   indexr   r   r   pk_valuer   r1   )rv   )r-   r   r=   r     s*    
zBaseModelFormSet.add_fields)NNr   NN)T)T)T)T)T)T)rN   r^   r_   __doc__rR   rl   r   r]   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   rw   r<   r<   )rv   r=   r!   )  s.    	



E



r   Fc             C   sv   t |dd}t |d|dkr4t |d|	dkr4tdt| |||	||
|||||d}t|||||||||d	}| |_|S )zC
    Returns a FormSet class for the given Django model class.
    ra   Nr*   r9   z]Calling modelformset_factory without defining 'fields' or 'exclude' explicitly is prohibited.)
r7   r*   r9   rT   rS   rU   rV   rW   rH   rX   )extramin_nummax_num	can_orderr   validate_minvalidate_max)rB   r   r%   r   rR   )rR   r7   rT   formsetr   r   r   r   r*   r9   rS   r   rU   rV   rW   rH   r   r   rX   metaFormSetr<   r<   r=   r"   A  s    	


c                   sh   e Zd ZdZd fdd	Z fddZ fdd	Zed
d ZdddZ	 fddZ
 fddZ  ZS )r#   z0A formset for child objects related to a parent.NFc       	         s   |d kr| j jj | _n|| _|| _|d kr4| jj}| jjd k	rX|jf | j j| ji}n|j	 }| j jh| _
tt| j||f||d| | jjjr| j j| jjjkrt| jjjtrt| jjj| jj_| jjjj| j j d S )N)r~   ry   )fkr   rR   r8   save_as_newr   r   filterr.   noner   rh   r#   r]   r7   r(   r*   r,   r   listr5   )	r[   r2   r3   r8   r   r~   ry   rY   r   )rv   r<   r=   r]   b  s     zBaseInlineFormSet.__init__c                s   | j r
dS tt| j S )Nr   )r   rh   r#   r   )r[   )rv   r<   r=   r   z  s    z$BaseInlineFormSet.initial_form_countc                s   t t| j|f|}| jrBd |j|j| jj< d |j|j| jj< | j	j
}| jjj| jjjjj
jkrt| j	| jjj}t|d|}t|j	| jj | |S )Nr   )rh   r#   r   r   r2   r4   r   r.   r   r8   r   r   r   rR   r(   rB   setattrget_attname)r[   r   rY   r7   Zfk_value)rv   r<   r=   r     s    z!BaseInlineFormSet._construct_formc             C   s   | j jj| jdjddS )N)rR   + )r   r   Zget_accessor_namerR   replace)clsr<   r<   r=   get_default_prefix  s    z$BaseInlineFormSet.get_default_prefixTc             C   sr   t |j| jj| j |jdd}t| j| jjj}t || jj t|d| |rX|j  |rnt	|drn|j
  |S )NF)r   r   r   )r   r8   r   r.   r   rB   r   r   r   rf   r   )r[   r7   r   r   r   r<   r<   r=   r     s    zBaseInlineFormSet.save_newc                s   t t| j|| | j| jkr0| jj}ddi}nP| jj}dt|jj|dt	| jj
i}| jjj| jjjjjjkr| jjj|d< | jjjr|jdd k	r| jjj|d }n
| jjj}|j rt| j|jd  t| jf||j|< d S )Nr   TrF   to_field)rh   r#   r   r   r   r.   rB   r*   rJ   r   Zverbose_namer   r   rR   r(   r   r8   r   r   	get_fieldr/   r   Zattnamer   )r[   r7   r   r.   rY   r   )rv   r<   r=   r     s    
 

zBaseInlineFormSet.add_fieldsc                s"    fdd|D }t t j|S )Nc                s   g | ]}| j jkr|qS r<   )r   r.   )rC   r0   )r[   r<   r=   rE     s    z>BaseInlineFormSet.get_unique_error_message.<locals>.<listcomp>)rh   r#   r   )r[   r   )rv   )r[   r=   r     s    z*BaseInlineFormSet.get_unique_error_message)NNNFNN)T)rN   r^   r_   r   r]   r   r   classmethodr   r   r   r   rw   r<   r<   )rv   r=   r#   `  s    
c                s  ddl m  |j}rfdd|jD }t|dkr~|d }t|  sh|jjkr|jjjj krt	djj
f n t|dkrt	d|jj
f nr fdd|jD }t|dkr|d }nFt|dkr|rd	S t	d
|jj
jj
f nt	d|jj
jj
f |S )aI  
    Finds and returns the ForeignKey from model to parent if there is one
    (returns None if can_fail is True and no such field exists). If fk_name is
    provided, assume it is the name of the ForeignKey field. Unless can_fail is
    True, an exception is raised if there is no ForeignKey from model to
    parent_model.
    r   )r   c                s   g | ]}|j  kr|qS r<   )r.   )rC   r;   )fk_namer<   r=   rE     s    z$_get_foreign_key.<locals>.<listcomp>r   z)fk_name '%s' is not a ForeignKey to '%s'.z'%s' has no field named '%s'.c                s8   g | ]0}t | r|jjks0|jjjj kr|qS r<   )r,   r   rR   r(   get_parent_list)rC   r;   )r   parent_modelr<   r=   rE     s    
Nz'%s' has no ForeignKey to '%s'.z*'%s' has more than one ForeignKey to '%s'.)r   r   r(   r*   r   r,   r   rR   r   r{   rF   )r   rR   r   Zcan_failr:   Zfks_to_parentr   r<   )r   r   r   r=   _get_foreign_key  s:    	
r   r   Tc             C   sX   t | ||d}|jrd}
|||||	|||||
||||||||d}t|f|}||_|S )z
    Returns an ``InlineFormSet`` for the given kwargs.

    You must provide ``fk_name`` if ``model`` has more than one ``ForeignKey``
    to ``parent_model``.
    )r   r   )r7   rT   r   r   r   r   r*   r9   r   r   rS   r   r   rU   rV   rW   rH   rX   )r   uniquer"   r   )r   rR   r7   r   r   r*   r9   r   r   r   r   rT   rS   r   rU   rV   rW   rH   r   r   rX   r   rY   r   r<   r<   r=   r$     s0    c                   s@   e Zd ZdZeZdediZ fddZdd Z	dd	 Z
  ZS )
r   zw
    A basic integer field that deals with validating the given value to a
    given parent instance in an inline.
    invalid_choicezEThe inline foreign key did not match the parent instance primary key.c                sp   || _ |jdd| _|jdd | _| j d k	rR| jrFt| j | j|d< n| j j|d< d|d< tt| j|| d S )Nr   Fr   r   r   )	parent_instancerg   r   r   rB   r   rh   r   r]   )r[   r  argsrY   )rv   r<   r=   r]   3  s    
zInlineForeignKeyField.__init__c             C   s`   || j kr| jrd S | jS | jr0t| j| j}n| jj}t|t|krZt| jd dd| jS )Nr  )r   )	r   r   r  r   rB   r   r   r   rH   )r[   rc   origr<   r<   r=   r   ?  s    
zInlineForeignKeyField.cleanc             C   s   dS )NFr<   )r[   r   r2   r<   r<   r=   r   N  s    z!InlineForeignKeyField.has_changed)rN   r^   r_   r   r   r1   r   default_error_messagesr]   r   r   rw   r<   r<   )rv   r=   r   )  s   r   c               @   s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
ModelChoiceIteratorc             C   s   || _ |j| _d S )N)r0   ry   )r[   r0   r<   r<   r=   r]   S  s    zModelChoiceIterator.__init__c             c   sP   | j jd k	rd| j jfV  | jj }|js2|j }x|D ]}| j|V  q8W d S )Nr   )r0   empty_labelry   allZ_prefetch_related_lookupsiteratorchoice)r[   ry   r   r<   r<   r=   __iter__W  s    

zModelChoiceIterator.__iter__c             C   s   t | j| jjd k	rdnd S )Nr   r   )r   ry   r0   r  )r[   r<   r<   r=   __len__a  s    zModelChoiceIterator.__len__c             C   s   | j j|| j j|fS )N)r0   prepare_valuelabel_from_instance)r[   r   r<   r<   r=   r  d  s    zModelChoiceIterator.choiceN)rN   r^   r_   r]   r  r  r  r<   r<   r<   r=   r  R  s   
r  c                   s   e Zd ZdZdediZddd	Zd
d Z fddZdd Z	dd Z
ee	e
Zdd Zdd ZeeejZ fddZdd Zdd Zdd Z  ZS )r   z1A ChoiceField whose choices are a model QuerySet.r  zGSelect a valid choice. That choice is not one of the available choices.	---------TNr   c
             O   sL   |r|d k	rd | _ n|| _ tj| |||||f|
| || _|	| _|| _d S )N)r  r
   r]   ry   r   to_field_name)r[   ry   r  r   r1   rF   r   rG   r  r   r  rY   r<   r<   r=   r]   q  s    
zModelChoiceField.__init__c             C   s   t | jr| j S | jS )z
        Returns ``limit_choices_to`` for this form field.

        If it is a callable, it will be invoked and the result will be
        returned.
        )rP   r   )r[   r<   r<   r=   rz     s    
z%ModelChoiceField.get_limit_choices_toc                s   t t| j|}|j|_|S )N)rh   r	   __deepcopy__ry   )r[   memoresult)rv   r<   r=   r    s    zModelChoiceField.__deepcopy__c             C   s   | j S )N)r   )r[   r<   r<   r=   _get_queryset  s    zModelChoiceField._get_querysetc             C   s   || _ | j| j_d S )N)r   choicesr1   )r[   ry   r<   r<   r=   _set_queryset  s    zModelChoiceField._set_querysetc             C   s   t |S )z
        This method is used to convert objects into strings; it's used to
        generate the labels for the choices presented by this object. Subclasses
        can override this method to customize the display of the choices.
        )r   )r[   r   r<   r<   r=   r    s    z$ModelChoiceField.label_from_instancec             C   s   t | dr| jS t| S )N_choices)rf   r  r  )r[   r<   r<   r=   _get_choices  s    
	zModelChoiceField._get_choicesc                s2   t |dr"| jr|j| jS |jS tt| j|S )Nr(   )rf   r  Zserializable_valuer   rh   r   r  )r[   rc   )rv   r<   r=   r    s
    
zModelChoiceField.prepare_valuec             C   sf   || j krd S y | jpd}| jjf ||i}W n2 tt| jjjfk
r`   t| j	d ddY nX |S )Nr   r  )r   )
r   r  ry   rJ   r{   rQ   rR   ZDoesNotExistr   rH   )r[   rc   keyr<   r<   r=   r     s    

zModelChoiceField.to_pythonc             C   s   t j| |S )N)r
   validate)r[   rc   r<   r<   r=   r    s    zModelChoiceField.validatec             C   s6   |d k	r|nd}|d k	r|nd}t | j|t |kS )Nr   )r   r  )r[   r   r2   initial_valueZ
data_valuer<   r<   r=   r     s    zModelChoiceField.has_changed)r  TNNNr   NN)rN   r^   r_   r   r   r  r]   rz   r  r  r  propertyry   r  r  r	   Z_set_choicesr  r  r   r  r   rw   r<   r<   )rv   r=   r   h  s"     


c                   sn   e Zd ZdZeZeZedededdZ	d fd	d
	Z
dd Zdd Zdd Z fddZdd Z  ZS )r   z9A MultipleChoiceField whose choices are a model QuerySet.zEnter a list of values.zESelect a valid choice. %(value)s is not one of the available choices.z0"%(pk)s" is not a valid value for a primary key.)r   r  invalid_pk_valueTNr   c       	         s(   t t| j|d |||||f|| d S )N)rh   r   r]   )	r[   ry   r   r1   rF   r   rG   r  rY   )rv   r<   r=   r]     s    
z!ModelMultipleChoiceField.__init__c             C   s   |sg S t | j|S )N)r   _check_values)r[   rc   r<   r<   r=   r     s    z"ModelMultipleChoiceField.to_pythonc             C   sz   | j |}| jr*| r*t| jd ddn| j rB| rB| jj S t|ttfsbt| jd dd| j	|}| j
| |S )Nr   )r   r   )r  r   r   rH   ry   r   r,   r   r   r  Zrun_validators)r[   rc   r   r<   r<   r=   r     s    



zModelMultipleChoiceField.cleanc                s   | j pd yt|}W n& tk
r<   t| jd ddY nX xT|D ]L}y| jjf  |i W qD ttfk
r   t| jd dd|idY qDX qDW | jjf d  |i}t fdd|D }x0|D ](}t	||krt| jd	 d	d
|idqW |S )z
        Given a list of possible PK values, returns a QuerySet of the
        corresponding objects. Raises a ValidationError if a given value is
        invalid (not a valid PK, not in the queryset, etc.)
        r   r   )r   r  )r   paramsz%s__inc             3   s   | ]}t t| V  qd S )N)r   rB   )rC   r   )r  r<   r=   r     s    z9ModelMultipleChoiceField._check_values.<locals>.<genexpr>r  rc   )
r  	frozensetrQ   r   rH   ry   r   r{   rl   r   )r[   rc   r   r   Zpksvalr<   )r  r=   r    s0    


z&ModelMultipleChoiceField._check_valuesc                sH   t |dr8t|tj r8t |d r8 fdd|D S tt j|S )Nr  r(   c                s   g | ]}t tj|qS r<   )rh   r   r  )rC   re   )rv   r[   r<   r=   rE      s    z:ModelMultipleChoiceField.prepare_value.<locals>.<listcomp>)rf   r,   r   r   rh   r   r  )r[   rc   )rv   )r[   r=   r    s
    
z&ModelMultipleChoiceField.prepare_valuec             C   s^   |d krg }|d krg }t |t |kr,dS tdd | j|D }tdd |D }||kS )NTc             s   s   | ]}t |V  qd S )N)r   )rC   rc   r<   r<   r=   r   *  s    z7ModelMultipleChoiceField.has_changed.<locals>.<genexpr>c             s   s   | ]}t |V  qd S )N)r   )rC   rc   r<   r<   r=   r   +  s    )r   rl   r  )r[   r   r2   Zinitial_setZdata_setr<   r<   r=   r   #  s    z$ModelMultipleChoiceField.has_changed)TNNNr   )rN   r^   r_   r   r   r1   r   Zhidden_widgetr   r  r]   r   r   r  r  r   rw   r<   r<   )rv   r=   r     s    %c             C   s*   | d k	o(t | do(| jjd k	p(| jjd k	S )Nr(   )rf   r(   r*   r9   )rI   r<   r<   r=   modelform_defines_fields/  s    
r#  )r   r   r   r   r   r   r    r!   r"   r#   r$   r%   )NN)NN)	NNNNNNNNN)NF)=r   
__future__r   collectionsr   	itertoolsr   Zdjango.core.exceptionsr   r   r   r   Zdjango.forms.fieldsr	   r
   Zdjango.forms.formsr   r   Zdjango.forms.formsetsr   r   Zdjango.forms.utilsr   Zdjango.forms.widgetsr   r   r   Zdjango.utilsr   Zdjango.utils.encodingr   r   Zdjango.utils.textr   r   Zdjango.utils.translationr   r   r   r&   r    r>   r   r   r   rZ   r`   r   with_metaclassr   r%   r!   r"   r#   r   r$   r   r  r   r   r#  r<   r<   r<   r=   <module>   sp      
'
   
RG DR  f
7&)j]