U
     5i/                     @   s  d 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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 Z#d>ddddZ$G dd dZ%G dd deZ&G dd deZ'G dd de'e&d Z(e(dddddddddf
d!d"Z)G d#d$ d$eZ*e(de*d%d&d&ddddd&dddddd&ddddfd'd(Z+G d)d* d*e*Z,d?d+d,Z-e(e,dddd-d&ddddd&dddddd&ddddfd.d/Z.G d0d1 d1e
Z/G d2d3 d3Z0G d4d5 d5Z1G d6d7 d7e	Z2G d8d9 d9e2Z3d:d; Z4dS )@z[
Helper functions for creating Form classes from Django models
and database field objects.
    )chain)NON_FIELD_ERRORS
FieldErrorImproperlyConfiguredValidationError)ChoiceFieldField)BaseFormDeclarativeFieldsMetaclass)BaseFormSetformset_factory)	ErrorList)HiddenInputMultipleHiddenInputRadioSelectSelectMultiple)capfirstget_text_list)gettextgettext_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 }|jD ]}|jr"t||js"|j|krDq"|dk	rX|j|krXq"|rh|j|krhq"|	 r| |j j
j| j| j| |jr||j| |j j
jkrq"t||jr|| q"||||j  q"|D ]}||||j  q|S )z
    Construct and return a model instance from the bound ``form``'s
    ``cleaned_data``, but do 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_prefixgetempty_valuesZ	FileFieldappendsave_form_data)	forminstancer&   excluder#   optsr%   Zfile_field_listf r:   7/tmp/pip-unpacked-wheel-gcyiijx6/django/forms/models.pyconstruct_instance   s4    
"r<   c                 C   sh   | j }i }t|j|j|jD ]F}t|dds.q|dk	rB|j|krBq|rR|j|krRq|| ||j< q|S )a  
    Return 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, return only the
    named.

    ``exclude`` is an optional list of field names. If provided, exclude the
    named from the returned dict, even if they are listed in the ``fields``
    argument.
    r'   FN)r$   r   concrete_fieldsprivate_fieldsmany_to_manygetattrr*   Zvalue_from_object)r6   r&   r7   r8   r.   r9   r:   r:   r;   r   G   s    r   c                 C   s   ddl m}m}m} t| dr|t| dr||  }|r||}t||sL|f |}|||ddM }| j|| jj	j
|| _dS )z=Apply limit_choices_to to the formfield's queryset if needed.r   )ExistsOuterRefQquerysetget_limit_choices_topkrF   N)django.db.modelsrA   rB   rC   hasattrrE   r(   rD   filtermodelZ_base_manager)	formfieldrA   rB   rC   limit_choices_toZcomplex_filterr:   r:   r;   #apply_limit_choices_to_to_formfield`   s    

rN   Tapply_limit_choices_toc
                   s  i g | j }ddlm   fdd|jD }tt|j||jD ]}t|dds|dk	rB|j	|krBdksx|j	krBt
d|j	| jf qB|dk	r|j	|krqBr|j	krqBi }|r|j	|kr||j	 |d	< |tks|r|j	|krd
|d< |r|j	|kr||j	 |d< |r0|j	|kr0||j	 |d< |rP|j	|krP||j	 |d< |	rp|j	|	krp|	|j	 |d< |dkr|jf |}n t|stdn||f|}|r|
rt| ||j	< qB|j	 qB|rfdd|D S )a4  
    Return a dictionary containing form fields for the given model.

    ``fields`` is an optional list of field names. If provided, return only the
    named fields.

    ``exclude`` is an optional list of field names. If provided, exclude the
    named fields 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.

    ``apply_limit_choices_to`` is a boolean indicating if limit_choices_to
    should be applied to a field's queryset.
    r   )r   c                    s   g | ]}t | r|qS r:   )r(   .0r9   )
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 fieldr-   TZlocalizelabel	help_texterror_messages
form_classz1formfield_callback must be a function or callablec                    s,   i | ]$} r| kr|kr| |qS r:   )r1   rQ   )r7   
field_dictignoredr:   r;   
<dictcomp>   s      z$fields_for_model.<locals>.<dictcomp>)r$   rH   r   r>   sortedr   r=   r?   r@   r*   r   __name__r   rL   callable	TypeErrorrN   r3   )rK   r&   r7   widgetsformfield_callbacklocalized_fieldslabels
help_textsrW   field_classesrP   r8   Zsortable_private_fieldsr9   kwargsrL   r:   )rS   r7   rY   rZ   r;   r   p   sf    " 


r   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 )
NrK   r&   r7   r`   rb   rc   rd   rW   re   )
r@   rK   r&   r7   r`   rb   rc   rd   rW   re   )selfoptionsr:   r:   r;   __init__   s    zModelFormOptions.__init__)N)r]   
__module____qualname__rj   r:   r:   r:   r;   rg      s   rg   c                       s   e Zd Z fddZ  ZS )ModelFormMetaclassc                    s~  d }|D ]&}t |drt |jdr|jj} q0q|d|}t | |||}|tfkr\|S tt|dd  }|_	dD ]:}	t||	}
t
|
trv|
tkrvd|j|	|
d }t|qv|jrn|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}d	d
 | D }||j}|r`d}|d||jjf }t|||j n|j}||_ |S )NMetara   )r&   r7   rb   zP%(model)s.Meta.%(opt)s cannot be a string. Did you mean to type: ('%(value)s',)?)rK   optvaluez|Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form %s needs updating.FrO   c                 S   s   h | ]\}}|s|qS r:   r:   )rR   kvr:   r:   r;   	<setcomp>  s      z-ModelFormMetaclass.__new__.<locals>.<setcomp>z&Unknown field(s) (%s) specified for %sz, )!rI   rn   ra   popsuper__new__r   rg   r@   r$   r(   strr   r]   r_   rK   r&   r7   r   r   r`   rb   rc   rd   rW   re   items
differenceZdeclared_fieldsjoinr   updateZbase_fields)Zmcsr*   basesattrsZbase_formfield_callbackbra   	new_classr8   ro   rp   msgr&   Znone_model_fieldsZmissing_fieldsmessage	__class__r:   r;   rv      sl    



       	
zModelFormMetaclass.__new__)r]   rk   rl   rv   __classcell__r:   r:   r   r;   rm      s   rm   c                       st   e Zd Zddddded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   Nid_%sFc                    s   | j }|jd krtd|	d kr0| | _i }n|	| _t|	|j|j}|d k	rX|| d| _t	 j
|||||||||
|d
 | j D ]}t| qd S )Nz'ModelForm has no model class specified.F)use_required_attributerenderer)r$   rK   
ValueErrorr6   r   r&   r7   r{   _validate_uniqueru   rj   valuesrN   )rh   r.   r/   auto_idprefixinitialerror_classZlabel_suffixZempty_permittedr6   r   r   r8   Zobject_datarL   r   r:   r;   rj     s2    


       zBaseModelForm.__init__c                 C   s   g }| j jjD ]}|j}|| jkr0||j q| jjrR|| jjkrR||j q| jjrt|| jjkrt||j q|| jkr||j q| j| }| j|}|j	s|j
s||jkr||j q|S )z
        For backwards-compatibility, exclude several types of fields from model
        validation. See tickets #12507, #12521, #12553.
        )r6   r$   r&   r*   r3   r7   _errorsr%   r1   blankrequiredr2   )rh   r7   r9   r,   Z
form_fieldZfield_valuer:   r:   r;   _get_validation_exclusions<  s     

	
z(BaseModelForm._get_validation_exclusionsc                 C   s   d| _ | jS )NT)r   r%   rh   r:   r:   r;   cleane  s    zBaseModelForm.cleanc                 C   s   | j }t|dr|j}nt|i}| D ]p\}}|tkrT|jrTt|jkrT|jt }n|| jkr(| j| j}nq(|D ]$}t|trr|j	|krr||j	 |_
qrq(| d | d S )N
error_dict)r$   rI   r   r   rx   rW   r&   r(   r   coder   Z	add_error)rh   errorsr8   r   r,   messagesrW   r   r:   r:   r;   _update_errorsi  s$    


zBaseModelForm._update_errorsc              
   C   s   | j }|  }| j D ]\}}t|tr|| qzt| | j|j|j	| _W n, t
k
r| } z| | W 5 d }~X Y nX z| jj|dd W n, t
k
r } z| | W 5 d }~X Y nX | jr|   d S )NF)r7   validate_unique)r$   r   r&   rx   r(   InlineForeignKeyFieldr3   r<   r6   r7   r   r   Z
full_cleanr   r   )rh   r8   r7   r*   r,   er:   r:   r;   _post_clean  s    	
zBaseModelForm._post_cleanc              
   C   sL   |   }z| jj|d W n, tk
rF } z| | W 5 d}~X Y nX dS )z
        Call the instance's validate_unique() method and update the form's
        validation errors if any were raised.
        r7   N)r   r6   r   r   r   )rh   r7   r   r:   r:   r;   r     s
    zBaseModelForm.validate_uniquec                 C   s   | j }| jj}| jj}| jj}t|j|jD ]N}t|ds<q,|rL|j	|krLq,|r\|j	|kr\q,|j	|kr,|
| j||j	  q,dS )zS
        Save the many-to-many fields and generic relations for this form.
        r4   N)r%   r$   r7   r&   r6   r   r?   r>   rI   r*   r4   )rh   r%   r7   r&   r8   r9   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  |   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   r6   r$   Zobject_name_stateaddingsaver   save_m2m)rh   commitr:   r:   r;   r     s    

zBaseModelForm.save)T)r]   rk   rl   r   rj   r   r   r   r   r   r   r   alters_datar   r:   r:   r   r;   r     s"       )
r   c                   @   s   e Zd ZdS )r   N)r]   rk   rl   r:   r:   r:   r;   r     s   r   )	metaclassc                 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 |dr|jfnd}td||}|rt||_| jd }||d}t|dddkrt|dddkrtdt|||f|S )al  
    Return a ModelForm containing form fields for the given model. You can
    optionally pass a `form` argument to use as a starting point for
    constructing the ModelForm.

    ``fields`` is an optional list of field names. If provided, include only
    the named fields in the returned fields. If omitted or '__all__', use all
    fields.

    ``exclude`` is an optional list of field names. If provided, exclude the
    named fields 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.
    rK   Nr&   r7   r`   rb   rc   rd   rW   re   rn   r:   ZForm)rn   ra   zZCalling modelform_factory without defining 'fields' or 'exclude' explicitly is prohibited.)rI   rn   typestaticmethodra   r]   r@   r   )rK   r5   r&   r7   ra   r`   rb   rc   rd   rW   re   r}   r|   rn   
class_nameZform_class_attrsr:   r:   r;   r!     s@    '

r!   c                       s   e Zd ZdZdZe Zd*d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d0d&d'Z fd(d)Z  ZS )1r   zO
    A ``FormSet`` for editing a queryset and/or adding new objects to it.
    Nr   )r   c                   s,   || _ || _t jf ||||d| d S )N)r.   r/   r   r   )rD   initial_extraru   rj   )rh   r.   r/   r   r   rD   r   rf   r   r:   r;   rj   ?  s    zBaseModelFormSet.__init__c                    s   | j st|  S t  S )z=Return the number of forms that are required in this FormSet.)is_boundlenget_querysetru   initial_form_countr   r   r:   r;   r   E  s    z#BaseModelFormSet.initial_form_countc                 C   s*   t | dsdd |  D | _| j|S )N_object_dictc                 S   s   i | ]}|j |qS r:   rG   rR   or:   r:   r;   r[   M  s      z5BaseModelFormSet._existing_object.<locals>.<dictcomp>)rI   r   r   r1   )rh   rF   r:   r:   r;   _existing_objectK  s    
z!BaseModelFormSet._existing_objectc                 C   s   |j dk	r|j  }q |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rh   r,   r:   r:   r;   _get_to_pythonP  s    
zBaseModelFormSet._get_to_pythonc                    s  ||   k }|r| jrd| || jjjjf }z| j| }W n tk
rR   Y qX | 	| jjj}z||}W n t
k
r   Y qX | ||d< q|  | |d< n6| jrz| j||     |d< W n tk
r   Y nX t j|f|}|rd|j| jjjj _|S )Nz%s-%sr6   r   T)r   r   r0   rK   r$   rF   r*   r.   KeyErrorr   r   r   r   r   
IndexErrorru   _construct_formr&   r   )rh   irf   Zpk_requiredZpk_keyrF   r   r5   r   r:   r;   r   Y  s0    z BaseModelFormSet._construct_formc                 C   sL   t | dsF| jd k	r| j}n| jj }|js@|| jjjj	}|| _
| j
S )N	_queryset)rI   rD   rK   _default_managerr   ZorderedZorder_byr$   rF   r*   r   )rh   qsr:   r:   r;   r   {  s    

zBaseModelFormSet.get_querysetTc                 C   s   |j |dS )z8Save and return a new model instance for the given form.r   r   rh   r5   r   r:   r:   r;   save_new  s    zBaseModelFormSet.save_newc                 C   s   |j |dS )z>Save and return an existing model instance for the given form.r   r   )rh   r5   r6   r   r:   r:   r;   save_existing  s    zBaseModelFormSet.save_existingc                 C   s   |r|   dS )z#Deletes an existing model instance.N)delete)rh   objr   r:   r:   r;   delete_existing  s    z BaseModelFormSet.delete_existingc                    s0   |sg  _  fdd}| _ | | S )z
        Save model instances for every form, adding and changing instances
        as necessary, and return the list of instances.
        c                     s    j D ]} |   qd S N)saved_formsr   )r5   r   r:   r;   r     s    
z'BaseModelFormSet.save.<locals>.save_m2m)r   r   save_existing_objectssave_new_objects)rh   r   r   r:   r   r;   r     s
    zBaseModelFormSet.savec                 C   s   |    d S r   )r   r   r:   r:   r;   r     s    zBaseModelFormSet.cleanc                    s  t  }t  }jfddjD }|D ]2   } jj|d\}}|| || q*g }|D ]\}}	t  }
|D ]  fdd|	D }tdd |D }|rxd |krx||
kr |	|	 j
 gjd jt< |	D ]}| jkr j|= q|
| qxqf|D ]}t  }
|\}}}}|D ]  jr, j| d k	r, j| d k	r,|dkr~ j| }|j|j|jf}nt j| |f} j| f| }||
kr|| j
 gjd jt<  j|= |
| q,q|rt|d S )	Nc                    s    g | ]}|  r| kr|qS r:   )Zis_valid)rR   r5   )forms_to_deleter:   r;   rT     s       z4BaseModelFormSet.validate_unique.<locals>.<listcomp>r   c                 3   s0   | ](}| j kr|jkr|n j | V  qd S r   )r%   unique_fieldsrR   r,   )r5   rh   r:   r;   	<genexpr>  s    
z3BaseModelFormSet.validate_unique.<locals>.<genexpr>c                 s   s6   | ].}t |d r| nt|tr*t|n|V  qdS )_get_pk_valN)rI   r   r(   listtuple)rR   dr:   r:   r;   r     s   )r   date)setdeleted_formsZformsr   r6   Z_get_unique_checksr{   r   r3   get_unique_error_messager   get_form_errorr   r   r   r%   addyearmonthdayr@   get_date_error_messager   )rh   Zall_unique_checksZall_date_checksZvalid_formsr7   Zunique_checksZdate_checksr   Zuclassunique_checkZ	seen_dataZrow_datar,   
date_checklookupZ
unique_forr   Z	date_datar.   r:   )r5   r   rh   r;   r     sh    






z BaseModelFormSet.validate_uniquec                 C   s>   t |dkr tdd|d i S tddt|tdi S d S )N   z0Please correct the duplicate data for %(field)s.r,   r   zFPlease correct the duplicate data for %(field)s, which must be unique.and)r   r   r   _rh   r   r:   r:   r;   r     s      z)BaseModelFormSet.get_unique_error_messagec                 C   s$   t d|d |d t|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   )
field_nameZ
date_fieldr   )r   rw   )rh   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}| jD ]z}|j}|jd kr<q&||kr`| j| | j||d q&| r&| j ||j	f || j
|||d |s&| j| q&|S Nr   )Zchanged_objectsZdeleted_objectsZinitial_formsr   r6   rF   r3   r   has_changedZchanged_datar   r   )rh   r   Zsaved_instancesr   r5   r   r:   r:   r;   r     s&    

z&BaseModelFormSet.save_existing_objectsc                 C   sZ   g | _ | jD ]F}| sq| jr,| |r,q| j | j||d |s| j| q| j S r   )Znew_objectsZextra_formsr   
can_deleteZ_should_delete_formr3   r   r   )rh   r   r5   r:   r:   r;   r   .  s    
z!BaseModelFormSet.save_new_objectsc           	         s(  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:z |dk	r|  | j}nd}W n tk
r   d}Y nX t|||fr|jjj }n| jj }||jjj}|jjr|jj| jjt}nt}t||d|d|j	| jj< t || dS )z0Add a hidden field for the object's primary key.r   )r)   
ForeignKeyOneToOneFieldc                    s6   | j  p4| jp4t|  p4| jo4| jjo4| jjjjS r   )r'   Zauto_createdr(   r   Zparent_linkrK   r$   rF   rG   r)   pk_is_not_editabler:   r;   r   F  s    z7BaseModelFormSet.add_fields.<locals>.pk_is_not_editableNF)r   r   r-   )rH   r)   r   r   rK   r$   rF   	_pk_fieldr*   r&   r   r6   r   r   r   r   r(   r   r   Zusingdbr`   r1   r   r   ru   
add_fields)	rh   r5   indexr   r   rF   Zpk_valuer   r-   r   r   r;   r   <  s*    
zBaseModelFormSet.add_fields)NNr   NN)T)T)T)T)T)T)r]   rk   rl   __doc__rK   r   r   rj   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r:   r:   r   r;   r   6  s4     	"



O



r   r   Fc                 C   s|   t |dd}t |d|dkr4t |d|	dkr4tdt| |||	||
|||||d}t||||||||||||d}| |_|S )z8Return a FormSet class for the given Django model class.rn   Nr&   r7   z]Calling modelformset_factory without defining 'fields' or 'exclude' explicitly is prohibited.)
r5   r&   r7   ra   r`   rb   rc   rd   rW   re   )
extramin_nummax_num	can_orderr   validate_minvalidate_maxabsolute_maxcan_delete_extrar   )r@   r   r!   r   rK   )rK   r5   ra   formsetr   r   r   r   r&   r7   r`   r   rb   rc   rd   rW   r   r   re   r   r   r   metaFormSetr:   r:   r;   r   h  s6    
      r   c                       sl   e Zd ZdZd fdd	Z fddZ fdd	Zed
d Zd f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 | _n|| _|| _|d kr4| jj}| jjd k	rX|jf | j j| ji}n|	 }| j jh| _
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 d S )N)r   rD   )fkr   rK   r6   save_as_newr   rF   rJ   r*   noner   ru   rj   r5   r$   r&   r(   r   r   r3   )	rh   r.   r/   r6   r   r   rD   rf   r   r   r:   r;   rj     s    zBaseInlineFormSet.__init__c                    s   | j r
dS t  S )Nr   )r   ru   r   r   r   r:   r;   r     s    z$BaseInlineFormSet.initial_form_countc                    s   t  j|f|}| jrlt|jdd }|d k	r4d|j_d |j|| jj< d |j|| j	j< |d k	rl||j_| j
j}| j	jj| j	jjjjjkrt| j
| j	jj}t|d|}t|j
| j	 | |S )N_mutableTrF   )ru   r   r   r@   r.   r  r0   r   r*   r   r6   rF   r   r   rK   r$   setattrZget_attname)rh   r   rf   r5   ZmutableZfk_valuer   r:   r;   r     s    z!BaseInlineFormSet._construct_formc                 C   s   | j jj| jdddS )N)rK   + )r   r   Zget_accessor_namerK   replace)clsr:   r:   r;   get_default_prefix  s    z$BaseInlineFormSet.get_default_prefixTc                    s$   t |j| jj| j t j||dS r   )r  r6   r   r*   ru   r   r   r   r:   r;   r     s    zBaseInlineFormSet.save_newc                    s   t  || | j| jkr,| jj}ddi}n(| jj}dt|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|dd k	r| jj|d }n
| jjj}| rt| j|jd  t| jf||j|< d S )Npk_fieldTrU   to_field)ru   r   r   r   r*   r@   r&   r1   r   Zverbose_namer   r   rK   r$   rF   r6   r   r   	get_fieldr+   r  Zattnamer   )rh   r5   r   r*   rf   r
  r   r:   r;   r     s"    
 

zBaseInlineFormSet.add_fieldsc                    s    fdd|D }t  |S )Nc                    s   g | ]}| j jkr|qS r:   )r   r*   r   r   r:   r;   rT     s      z>BaseInlineFormSet.get_unique_error_message.<locals>.<listcomp>)ru   r   r   r   r   r;   r     s    z*BaseInlineFormSet.get_unique_error_message)NNNFNN)T)r]   rk   rl   r   rj   r   r   classmethodr  r   r   r   r   r:   r:   r   r;   r     s         
r   c                    s@  ddl m  |j}rfdd|jD }t|dkr|d }j t| r|jjjj	rn|jjjj
ks|jjjj	s|jjkr|jjkrtdjjf n|std|jjf nzj  fdd|jD }t|dkr|d }nB|s$|r
d	S td
|jjjjf ntd|jjjjf |S )aD  
    Find and return the ForeignKey from model to parent if there is one
    (return 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, raise an exception if there isn't a ForeignKey from model to
    parent_model.
    r   )r   c                    s   g | ]}|j  kr|qS r:   )r*   rQ   fk_namer:   r;   rT     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                    sN   g | ]F}t | r|jjksF|jjksF|jjjjr|jjjjkr|qS r:   )r(   r   rK   r$   proxyproxy_for_modelrQ   )r   parent_listparent_modelr:   r;   rT     s   
Nz'%s' has no ForeignKey to '%s'.zR'%s' has more than one ForeignKey to '%s'. You must specify a 'fk_name' attribute.)rH   r   r$   r&   r   Zget_parent_listr(   r   rK   r  r  r   rU   )r  rK   r  Zcan_failr8   Zfks_to_parentr   r:   )r   r  r  r  r;   _get_foreign_key  s`    	









r  r   c                 C   s^   t | ||d}|jrd}
|||||	|||||
|||||||||||d}t|f|}||_|S )z
    Return an ``InlineFormSet`` for the given kwargs.

    ``fk_name`` must be provided if ``model`` has more than one ``ForeignKey``
    to ``parent_model``.
    r  r   )r5   ra   r   r   r   r   r&   r7   r   r   r`   r   r   rb   rc   rd   rW   re   r   r   r   )r  uniquer   r   )r  rK   r5   r   r  r&   r7   r   r   r   r   ra   r`   r   rb   rc   rd   rW   r   r   re   r   r   r   r   rf   r   r:   r:   r;   r    0  s8    r    c                       sH   e Zd ZdZeZdediZddd 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_choicez3The inline value did not match the parent instance.FN)r	  r
  c                   s\   || _ || _|| _| j d k	rB| jr6t| j | j|d< n| j j|d< d|d< t j|| d S )Nr   Fr   )parent_instancer	  r
  r@   rF   ru   rj   )rh   r  r	  r
  argsrf   r   r:   r;   rj   j  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   )	r2   r	  r  r
  r@   rF   rw   r   rW   )rh   rp   origr:   r:   r;   r   v  s    
zInlineForeignKeyField.cleanc                 C   s   dS )NFr:   )rh   r   r.   r:   r:   r;   r     s    z!InlineForeignKeyField.has_changed)r]   rk   rl   r   r   r-   r   default_error_messagesrj   r   r   r   r:   r:   r   r;   r   `  s    r   c                   @   s,   e Zd Zdd Zdd Zdd Zdd Zd	S )
ModelChoiceIteratorValuec                 C   s   || _ || _d S r   )rp   r6   )rh   rp   r6   r:   r:   r;   rj     s    z!ModelChoiceIteratorValue.__init__c                 C   s
   t | jS r   )rw   rp   r   r:   r:   r;   __str__  s    z ModelChoiceIteratorValue.__str__c                 C   s
   t | jS r   )hashrp   r   r:   r:   r;   __hash__  s    z!ModelChoiceIteratorValue.__hash__c                 C   s   t |tr|j}| j|kS r   )r(   r  rp   )rh   otherr:   r:   r;   __eq__  s    
zModelChoiceIteratorValue.__eq__N)r]   rk   rl   rj   r  r  r   r:   r:   r:   r;   r    s   r  c                   @   s4   e Zd Zdd Zdd Zdd Zdd Zd	d
 ZdS )ModelChoiceIteratorc                 C   s   || _ |j| _d S r   )r,   rD   r   r:   r:   r;   rj     s    zModelChoiceIterator.__init__c                 c   sH   | j jd k	rd| j jfV  | j}|js.| }|D ]}| |V  q2d S )Nr  )r,   empty_labelrD   Z_prefetch_related_lookupsiteratorchoice)rh   rD   r   r:   r:   r;   __iter__  s    zModelChoiceIterator.__iter__c                 C   s   | j  | jjd k	rdnd S )Nr   r   )rD   countr,   r"  r   r:   r:   r;   __len__  s    zModelChoiceIterator.__len__c                 C   s   | j jd k	p| j S r   )r,   r"  rD   existsr   r:   r:   r;   __bool__  s    zModelChoiceIterator.__bool__c                 C   s   t | j||| j|fS r   )r  r,   prepare_valuelabel_from_instancerh   r   r:   r:   r;   r$    s    
zModelChoiceIterator.choiceN)r]   rk   rl   rj   r%  r'  r)  r$  r:   r:   r:   r;   r!    s
   
r!  c                
       s   e Zd ZdZdediZeZddddddddd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.z	---------TNr  F)	r"  r   r-   rU   r   rV   to_field_namerM   r   c       	         K   s^   t j| f|||||d| |r*|d k	s:t| jtrB|
sBd | _n|| _|| _|	| _|| _d S )N)r   r-   rU   r   rV   )	r   rj   r(   r-   r   r"  rD   rM   r-  )rh   rD   r"  r   r-   rU   r   rV   r-  rM   r   rf   r:   r:   r;   rj     s0       
zModelChoiceField.__init__c                 C   s   t | jr|  S | jS )z
        Return ``limit_choices_to`` for this form field.

        If it is a callable, invoke it and return the result.
        )r^   rM   r   r:   r:   r;   rE     s    
z%ModelChoiceField.get_limit_choices_toc                    s*   t t| |}| jd k	r&| j |_|S r   )ru   r   __deepcopy__rD   all)rh   memoresultr   r:   r;   r.    s    
zModelChoiceField.__deepcopy__c                 C   s   | j S r   )r   r   r:   r:   r;   _get_queryset  s    zModelChoiceField._get_querysetc                 C   s$   |d krd n|  | _| j| j_d S r   )r/  r   choicesr-   )rh   rD   r:   r:   r;   _set_queryset  s    zModelChoiceField._set_querysetc                 C   s   t |S )z
        Convert objects into strings and generate the labels for the choices
        presented by this object. Subclasses can override this method to
        customize the display of the choices.
        rw   r,  r:   r:   r;   r+    s    z$ModelChoiceField.label_from_instancec                 C   s   t | dr| jS | | S )N_choices)rI   r6  r#  r   r:   r:   r;   _get_choices  s    
	zModelChoiceField._get_choicesc                    s.   t |dr"| jr|| jS |jS t |S Nr$   )rI   r-  Zserializable_valuerF   ru   r*  rh   rp   r   r:   r;   r*    s
    
zModelChoiceField.prepare_valuec              
   C   s   || j krd S z8| jpd}t|| jjr2t||}| jjf ||i}W n8 tt| jjj	fk
r~   t
| jd dd|idY nX |S )NrF   r  rp   r   params)r2   r-  r(   rD   rK   r@   r1   r   r_   ZDoesNotExistr   rW   )rh   rp   keyr:   r:   r;   r     s    


zModelChoiceField.to_pythonc                 C   s   t | |S r   )r   validater9  r:   r:   r;   r=  %  s    zModelChoiceField.validatec                 C   s@   | j r
dS |d k	r|nd}|d k	r&|nd}t| |t|kS )NFr  )disabledrw   r*  )rh   r   r.   initial_valueZ
data_valuer:   r:   r;   r   (  s
    zModelChoiceField.has_changed)r]   rk   rl   r   r   r  r!  r#  rj   rE   r.  r2  r4  propertyrD   r+  r7  r   Z_set_choicesr3  r*  r   r=  r   r   r:   r:   r   r;   r     s6         

r   c                       sl   e Zd ZdZeZeZedededdZ	 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.u"   “%(pk)s” is not a valid value.)invalid_listr  invalid_pk_valuec                    s   t  j|fdd i| d S )Nr"  )ru   rj   )rh   rD   rf   r   r:   r;   rj   ;  s    z!ModelMultipleChoiceField.__init__c                 C   s   |sg S t | |S r   )r   _check_valuesr9  r:   r:   r;   r   >  s    z"ModelMultipleChoiceField.to_pythonc                 C   st   |  |}| jr(|s(t| jd ddn| js<|s<| j S t|ttfs\t| jd dd| 	|}| 
| |S )Nr   r  rA  )r*  r   r   rW   rD   r  r(   r   r   rC  Zrun_validators)rh   rp   r   r:   r:   r;   r   C  s    





zModelMultipleChoiceField.cleanc              
      s   | j pd zt|}W n& tk
r<   t| jd ddY nX |D ]L}z| jjf  |i W qB ttfk
r   t| jd dd|idY qBX qB| jjf d  |i} fdd|D }|D ](}t||krt| jd	 d	d
|idq|S )z
        Given a list of possible PK values, return a QuerySet of the
        corresponding objects. Raise a ValidationError if a given value is
        invalid (not a valid PK, not in the queryset, etc.)
        rF   rA  r  rB  r:  z%s__inc                    s   h | ]}t t| qS r:   )rw   r@   r   r<  r:   r;   rs   o  s     z9ModelMultipleChoiceField._check_values.<locals>.<setcomp>r  rp   )	r-  	frozensetr_   r   rW   rD   rJ   r   rw   )rh   rp   rF   r   Zpksvalr:   rD  r;   rC  T  s6    
z&ModelMultipleChoiceField._check_valuesc                    sD   t |dr8t|ts8t |ds8t j  fdd|D S t |S )Nr%  r$   c                    s   g | ]} |qS r:   r:   )rR   rr   r*  r:   r;   rT   ~  s     z:ModelMultipleChoiceField.prepare_value.<locals>.<listcomp>)rI   r(   rw   ru   r*  r9  r   rG  r;   r*  y  s    
z&ModelMultipleChoiceField.prepare_valuec                 C   s`   | j r
dS |d krg }|d kr"g }t|t|kr6dS dd | |D }dd |D }||kS )NFTc                 S   s   h | ]}t |qS r:   r5  rR   rp   r:   r:   r;   rs     s     z7ModelMultipleChoiceField.has_changed.<locals>.<setcomp>c                 S   s   h | ]}t |qS r:   r5  rH  r:   r:   r;   rs     s     )r>  r   r*  )rh   r   r.   Zinitial_setZdata_setr:   r:   r;   r     s    z$ModelMultipleChoiceField.has_changed)r]   rk   rl   r   r   r-   r   Zhidden_widgetr   r  rj   r   r   rC  r*  r   r   r:   r:   r   r;   r   0  s   %r   c                 C   s"   t | do | jjd k	p | jjd k	S r8  )rI   r$   r&   r7   )rX   r:   r:   r;   modelform_defines_fields  s    

rI  )NN)NN)	NNNNNNNNN)NF)5r   	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   r   Zdjango.utils.textr   r   Zdjango.utils.translationr   r   r   r"   r   r<   r   rN   r   rg   rm   r   r   r!   r   r   r   r  r    r   r  r!  r   r   rI  r:   r:   r:   r;   <module>   s   
)
          YH @    
U  4             
 d
D              
0)w_