o
    [h                     @   sr  d Z ddlmZ ddlmZmZmZmZ ddl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d	lmZ dd
lmZmZmZmZ ddl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'dZ(dAddZ)dAddZ*dd Z+									dBdddddZ,G dd dZ-G dd  d eZ.G d!d" d"eeZ/G d#d$ d$e/e.d%Z0e0dddddddddf
d&d'Z1G d(d) d)eeZ2e0de2d*d+d+ddddd+dddddd+ddddd+fd,d-Z3G d.d/ d/e2Z4dCd0d1Z5e0e4dddd2d+ddddd+dddddd+ddddd+fd3d4Z6G d5d6 d6eZ7G d7d8 d8Z8G d9d: d:eZ9G d;d< d<eZ:G d=d> d>e:Z;d?d@ Z<dS )Dz[
Helper functions for creating Form classes from Django models
and database field objects.
    )chain)NON_FIELD_ERRORS
FieldErrorImproperlyConfiguredValidationErrorProhibitNullCharactersValidator)
AltersData)ChoiceFieldField)BaseFormDeclarativeFieldsMetaclass)BaseFormSetformset_factory)	ErrorList)HiddenInputMultipleHiddenInputRadioSelectSelectMultiple)BaseChoiceIterator)make_hashable)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|vr"q|dur,|j|vr,q|r4|j|v r4q|	 rX| |j j
j| j| j| |jrX||j| |j j
jv rXqt||jrd|| q||||j  q|D ]}||||j  qp|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@   z/home/ubuntu/experiments/live_experiments/Pythonexperiments/Otree/venv/lib/python3.10/site-packages/django/forms/models.pyconstruct_instance2   s:   


rB   c                 C   sh   | j }i }t|j|j|jD ]#}t|ddsq|dur!|j|vr!q|r)|j|v r)q|| ||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getattrr0   Zvalue_from_object)r<   r,   r=   r>   r4   r?   r@   r@   rA   r   b   s   r   c                 C   s   ddl m}m}m} t| drBt| drD|  }|rF|}t||s(|di |}|||ddM }| j|| jj	j
|| _dS dS dS dS )	z=Apply limit_choices_to to the formfield's queryset if needed.r   )ExistsOuterRefQquerysetget_limit_choices_topkrL   Nr@   )django.db.modelsrG   rH   rI   hasattrrK   r.   rJ   filtermodelZ_base_manager)	formfieldrG   rH   rI   limit_choices_toZcomplex_filterr@   r@   rA   #apply_limit_choices_to_to_formfield{   s   

rT   Tapply_limit_choices_toform_declared_fieldsc
                   s  |pi }i g | j }ddlm   fdd|jD }tt|j||jD ]}t|ddsJ|durI|j	|v rIdu s?|j	vrIt
d|j	| jf q%|durT|j	|vrTq%r\|j	v r\q%|j	|v rj||j	 |j	< q%i }|rz|j	|v rz||j	 |d	< |tks|r|j	|v rd
|d< |r|j	|v r||j	 |d< |r|j	|v r||j	 |d< |r|j	|v r||j	 |d< |	r|j	|	v r|	|j	 |d< |du r|jdi |}nt|std||fi |}|r|
rt| ||j	< q%|j	 q%|rfdd|D S )a  
    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.

    ``form_declared_fields`` is a dictionary of form fields created directly on
    a form.
    r   )r   c                    s   g | ]	}t | r|qS r@   )r.   .0r?   )
ModelFieldr@   rA   
<listcomp>   s
    
z$fields_for_model.<locals>.<listcomp>r-   FNzH'%s' cannot be specified for %s model form as it is a non-editable fieldr3   Tlocalizelabel	help_texterror_messages
form_classz1formfield_callback must be a function or callablec                    s,   i | ]} r
| vr|vr| |qS r@   )r7   rX   )r=   
field_dictignoredr@   rA   
<dictcomp>   s    
z$fields_for_model.<locals>.<dictcomp>r@   )r*   rN   r   rD   sortedr   rC   rE   rF   r0   r   __name__r"   rR   callable	TypeErrorrT   r9   )rQ   r,   r=   widgetsformfield_callbacklocalized_fieldslabels
help_textsr_   field_classesrV   rW   r>   Zsortable_private_fieldsr?   kwargsrR   r@   )rZ   r=   ra   rb   rA   r      sv   0




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 | _	t |d
d | _
d S )NrQ   r,   r=   rh   rj   rk   rl   r_   rm   ri   )rF   rQ   r,   r=   rh   rj   rk   rl   r_   rm   ri   )selfoptionsr@   r@   rA   __init__  s   zModelFormOptions.__init__N)re   
__module____qualname__rr   r@   r@   r@   rA   ro     s    ro   c                       s   e Zd Z fddZ  ZS )ModelFormMetaclassc                    sD  t  | |||}|tfkr|S tt|dd  }|_dD ]}t||}t|tr:|tkr:d|j	||d }t
|q|jr|jd u rN|jd u rNtd| |jtkrVd |_t|j|j|j|j|j|j|j|j|j|jd|jd}	dd	 |	 D }
|
|j}|rd
}|d||jj	f; }t||	|j n|j}	|	|_|S )NMeta)r,   r=   rj   zP%(model)s.Meta.%(opt)s cannot be a string. Did you mean to type: ('%(value)s',)?)rQ   optvaluez|Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form %s needs updating.FrU   c                 S   s   h | ]\}}|s|qS r@   r@   )rY   kvr@   r@   rA   	<setcomp>I  s    z-ModelFormMetaclass.__new__.<locals>.<setcomp>z&Unknown field(s) (%s) specified for %sz, )super__new__r   ro   rF   r*   r.   strr"   re   rg   rQ   r,   r=   r   r   rh   ri   rj   rk   rl   r_   rm   Zdeclared_fieldsitems
differencejoinr   updatebase_fields)mcsr0   basesattrs	new_classr>   rx   ry   msgr,   Znone_model_fieldsZmissing_fieldsmessage	__class__r@   rA   r~     sb   

	
zModelFormMetaclass.__new__)re   rt   ru   r~   __classcell__r@   r@   r   rA   rv     s    rv   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 u rtd|	d u r| | _i }n|	| _t|	|j|j}|d ur,|| d| _t	 j
|||||||||
|d
 | j D ]}t| qDd S )Nz'ModelForm has no model class specified.F)use_required_attributerenderer)r*   rQ   
ValueErrorr<   r   r,   r=   r   _validate_uniquer}   rr   valuesrT   )rp   r4   r5   auto_idprefixinitialerror_classZlabel_suffixZempty_permittedr<   r   r   r>   Zobject_datarR   r   r@   rA   rr   Z  s4   



zBaseModelForm.__init__c                 C   s   t  }| jjjD ][}|j}|| jvr||j q| jjr*|| jjvr*||j q| jjr;|| jjv r;||j q|| jv rG||j q| j| }| j	|}|j
sc|jsc||jv rc||j q|S )z
        For backwards-compatibility, exclude several types of fields from model
        validation. See tickets #12507, #12521, #12553.
        )setr<   r*   r,   r0   addr=   _errorsr+   r7   blankrequiredr8   )rp   r=   r?   r2   Z
form_fieldZfield_valuer@   r@   rA   _get_validation_exclusions  s*   


	
z(BaseModelForm._get_validation_exclusionsc                 C   s   d| _ | jS )NT)r   r+   rp   r@   r@   rA   clean  s   zBaseModelForm.cleanc                 C   s   | j }t|dr|j}nt|i}| D ]8\}}|tkr*|jr*t|jv r*|jt }n|| jv r6| j| j}nq|D ]}t|trK|j	|v rK||j	 |_
q9q| d | d S )N
error_dict)r*   rO   r   r   r   r_   r,   r.   r   coder   Z	add_error)rp   errorsr>   r   r2   messagesr_   r   r@   r@   rA   _update_errors  s*   



zBaseModelForm._update_errorsc              
   C   s   | j }|  }| j D ]\}}t|tr|| qzt| | j|j|j	| _W n t
y? } z| | W Y d }~nd }~ww z
| jj|dd W n t
ya } z| | W Y d }~nd }~ww | jrk|   d S d S )NF)r=   validate_unique)r*   r   r,   r   r.   InlineForeignKeyFieldr   rB   r<   r=   r   r   Z
full_cleanr   r   )rp   r>   r=   r0   r2   er@   r@   rA   _post_clean  s.   	


zBaseModelForm._post_cleanc              
   C   sN   |   }z
| jj|d W dS  ty& } z| | W Y d}~dS d}~ww )z
        Call the instance's validate_unique() method and update the form's
        validation errors if any were raised.
        )r=   N)r   r<   r   r   r   )rp   r=   r   r@   r@   rA   r     s   zBaseModelForm.validate_uniquec                 C   s   | j }| jj}| jj}| jj}t|j|jD ]'}t|dsq|r&|j	|vr&q|r.|j	|v r.q|j	|v r=|
| j||j	  qdS )zS
        Save the many-to-many fields and generic relations for this form.
        r:   N)r+   r*   r=   r,   r<   r   rE   rD   rO   r0   r:   )rp   r+   r=   r,   r>   r?   r@   r@   rA   	_save_m2m  s   

zBaseModelForm._save_m2mTc                 C   sZ   | j rtd| jjj| jjjrdf df |r&| j  |   | jS | 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   r<   r*   Zobject_name_stateaddingsaver   save_m2m)rp   commitr@   r@   rA   r     s$   
zBaseModelForm.saveT)re   rt   ru   r   rr   r   r   r   r   r   r   r   alters_datar   r@   r@   r   rA   r   Y  s*    .-! 
r   c                   @   s   e Zd ZdS )r   N)re   rt   ru   r@   r@   r@   rA   r   5  s    r   )	metaclassc                 C   s  d| i}|dur||d< |dur||d< |dur||d< |dur$||d< |dur,||d< |dur4||d< |	dur<|	|d	< |
durD|
|d
< t |drM|jfnd}td||}|r\t||_| jd }d|i}t|dddu ryt|dddu ryt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.
    rQ   Nr,   r=   rh   rj   rk   rl   r_   rm   rw   r@   ZFormzZCalling modelform_factory without defining 'fields' or 'exclude' explicitly is prohibited.)rO   rw   typestaticmethodri   re   rF   r   )rQ   r;   r,   r=   ri   rh   rj   rk   rl   r_   rm   r   r   rw   
class_nameZform_class_attrsr@   r@   rA   r'   9  s8   0

 r'   c                       s   e Zd 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d,d'd(Z fd)d*Z  ZS )-r#   zO
    A ``FormSet`` for editing a queryset and/or adding new objects to it.
    NFr   )r   c                   s0   || _ || _t jdi ||||d| d S )N)r4   r5   r   r   r@   )rJ   initial_extrar}   rr   )rp   r4   r5   r   r   rJ   r   rn   r   r@   rA   rr     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_querysetr}   initial_form_countr   r   r@   rA   r     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@   rM   rY   or@   r@   rA   rc         z5BaseModelFormSet._existing_object.<locals>.<dictcomp>)rO   r   r   r7   )rp   rL   r@   r@   rA   _existing_object  s   
z!BaseModelFormSet._existing_objectc                 C   s$   |j dur|j  }|j dus|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rp   r2   r@   r@   rA   _get_to_python  s   


zBaseModelFormSet._get_to_pythonc                    s  ||   k }|rR| jrId| || jjjjf }z| j| }W n	 ty(   Y nDw | 	| jjj}z||}W n	 t
y@   Y n,w | ||d< n#|  | |d< n| jrlz| j||     |d< W n	 tyk   Y nw t j|fi |}|rd|j| jjjj _|S )Nz%s-%sr<   r   T)r   r   r6   rQ   r*   rL   r0   r4   KeyErrorr   r   r   r   r   
IndexErrorr}   _construct_formr,   r   )rp   irn   Zpk_requiredZpk_keyrL   r   r;   r   r@   rA   r     s6   z BaseModelFormSet._construct_formc                 C   sL   t | ds#| jd ur| j}n| jj }|js || jjjj	}|| _
| j
S )N	_queryset)rO   rJ   rQ   _default_managerr   orderedZorder_byr*   rL   r0   r   )rp   qsr@   r@   rA   r     s   

zBaseModelFormSet.get_querysetTc                 C   s   |j |dS )z8Save and return a new model instance for the given form.r   r   rp   r;   r   r@   r@   rA   save_new     zBaseModelFormSet.save_newc                 C   s   |j |dS )z>Save and return an existing model instance for the given form.r   r   )rp   r;   objr   r@   r@   rA   save_existing  r   zBaseModelFormSet.save_existingc                 C   s   |r|   dS dS )z#Deletes an existing model instance.N)delete)rp   r   r   r@   r@   rA   delete_existing  s   z BaseModelFormSet.delete_existingc                    s@   |sg  _  fdd}| _ jr |S  | | 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 rs   )saved_formsr   )r;   r   r@   rA   r     s   

z'BaseModelFormSet.save.<locals>.save_m2m)r   r   	edit_onlysave_existing_objectssave_new_objects)rp   r   r   r@   r   rA   r     s   
zBaseModelFormSet.savec                 C   s   |    d S rs   )r   r   r@   r@   rA   r         zBaseModelFormSet.cleanc                    s  t  }t  }jfddjD }|D ]   } jj|dd\}}|| || qg }|D ]R\}}	t  }
|D ]H  fdd|	D }tdd |D }|rd |vr||
v r|	|	 j
 gjd jt< |	D ]}| jv r j|= qt|
| q=q4|D ]g}t  }
|\}}}}|D ]Y  jr j| d ur j| d ur|d	kr j| }|j|j|jf}n	t j| |f} j| f| }||
v r|| j
 gjd jt<  j|= |
| qq|rt|d S )
Nc                    s    g | ]}|  r| vr|qS r@   )Zis_valid)rY   r;   )forms_to_deleter@   rA   r[   (  s    z4BaseModelFormSet.validate_unique.<locals>.<listcomp>T)r=   Zinclude_meta_constraintsc                 3   s2    | ]}| j v r|jv r|n j | V  qd S rs   )r+   unique_fieldsrY   r2   )r;   rp   r@   rA   	<genexpr>=  s    
z3BaseModelFormSet.validate_unique.<locals>.<genexpr>c                 s   s*    | ]}t |d r| nt|V  qdS )_get_pk_valN)rO   r   r   )rY   dr@   r@   rA   r   C  s    

)r   date)r   deleted_formsZformsr   r<   Z_get_unique_checksr   tupler9   get_unique_error_messager   get_form_errorr   r   r   r+   r   yearmonthdayrF   get_date_error_messager   )rp   Zall_unique_checksZall_date_checksZvalid_formsr=   Zunique_checksZdate_checksr   Zuclassunique_checkZ	seen_dataZrow_datar2   
date_checklookupZ
unique_forr   Z	date_datar4   r@   )r;   r   rp   rA   r   #  s   


	

$

z BaseModelFormSet.validate_uniquec                 C   s:   t |dkrtdd|d i S tddt|tdi S )N   z0Please correct the duplicate data for %(field)s.r2   r   zFPlease correct the duplicate data for %(field)s, which must be unique.and)r   r   r   _rp   r   r@   r@   rA   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   r   )rp   r   r@   r@   rA   r     s   
z'BaseModelFormSet.get_date_error_messagec                 C   s   t dS )Nz*Please correct the duplicate values below.r   r   r@   r@   rA   r     s   zBaseModelFormSet.get_form_errorc                 C   s   g | _ g | _| jsg S g }| j}| jD ]<}|j}| sq||v r/| j| | j||d q| rO| j ||j	f || j
|||d |sO| j| q|S Nr   )Zchanged_objectsZdeleted_objectsZinitial_formsr   r<   
_is_pk_setr9   r   has_changedZchanged_datar   r   )rp   r   Zsaved_instancesr   r;   r   r@   r@   rA   r     s(   
z&BaseModelFormSet.save_existing_objectsc                 C   sZ   g | _ | jD ]#}| sq| jr| |rq| j | j||d |s)| j| q| j S r   )Znew_objectsZextra_formsr   
can_deleteZ_should_delete_formr9   r   r   )rp   r   r;   r@   r@   rA   r     s   
z!BaseModelFormSet.save_new_objectsc           	         s$  ddl m m}m} | jjj | _} fdd|s#|j|j	vr|j
r2|jjjr-dn|jj}nz|dur?|  | j}nd}W n tyM   d}Y nw t|||fr]|jjj }n| jj }||jjj}|jjrz|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  p| jpt|  p| jo| jjo| jjjjS rs   )r-   Zauto_createdr.   r   Zparent_linkrQ   r*   rL   rM   r/   pk_is_not_editabler@   rA   r     s   z7BaseModelFormSet.add_fields.<locals>.pk_is_not_editableNF)r   r   r3   )rN   r/   r   r   rQ   r*   rL   	_pk_fieldr0   r,   r   r<   r   r   r   r   r.   r   r   usingdbrh   r7   r   r    r}   
add_fields)	rp   r;   indexr   r   rL   Zpk_valuer   r3   r   r   rA   r     s2   zBaseModelFormSet.add_fields)NNr   NNr   )re   rt   ru   __doc__rQ   r   r   r   rr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r@   r@   r   rA   r#     s>    	"



`


r#   r   Fc                 C   s   t |dd}t |d|du rt |d|	du rtdt| |||	||
|||||d}t||||||||||||d}| |_||_|S )z8Return a FormSet class for the given Django model class.rw   Nr,   r=   z]Calling modelformset_factory without defining 'fields' or 'exclude' explicitly is prohibited.)
r;   r,   r=   ri   rh   rj   rk   rl   r_   rm   )
extramin_nummax_num	can_orderr   validate_minvalidate_maxabsolute_maxcan_delete_extrar   )rF   r   r'   r   rQ   r   )rQ   r;   ri   formsetr  r   r  r  r,   r=   rh   r  rj   rk   rl   r_   r  r  rm   r  r	  r   r   metaFormSetr@   r@   rA   r$     sH   r$   c                       sx   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 u r| j j | _n|| _|| _|d u r| jj}| j r-|jdi | j j| ji}n|	 }| j jh| _
t j||f||d| | jjjrq| j j| jjjvrst| jjjtret| jjj| jj_| jjj| j j d S d S d S )N)r   rJ   r@   )fkr   rQ   r<   save_as_newr   r   rP   r0   noner   r}   rr   r;   r*   r,   r.   r   listr9   )	rp   r4   r5   r<   r  r   rJ   rn   r   r   r@   rA   rr   A  s    

zBaseInlineFormSet.__init__c                    s   | j rdS t  S )Nr   )r  r}   r   r   r   r@   rA   r   `  s   
z$BaseInlineFormSet.initial_form_countc                    s   t  j|fi |}| jr8t|jdd }|d urd|j_d |j|| jj< d |j|| j	j< |d ur8||j_| j
j}| j	jj| j	jjjjjkrXt| j
| j	jj}t|d|}t|j
| j	j| |S )N_mutableTrL   )r}   r   r  rF   r4   r  r6   r   r0   r  r<   rL   r   r   rQ   r*   setattrattname)rp   r   rn   r;   ZmutableZfk_valuer   r@   rA   r   e  s   z!BaseInlineFormSet._construct_formc                 C   s   | j jj| jdddS )N)rQ   + )r  r   Zget_accessor_namerQ   replace)clsr@   r@   rA   get_default_prefix|  s   z$BaseInlineFormSet.get_default_prefixTc                    s$   t |j| jj| j t j||dS r   )r  r<   r  r0   r}   r   r   r   r@   rA   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rs|dd urT| jj|d }n| jjj}| rs|j| jj
jjjjksk|jsst| j|jd  t| jfi ||j|< d S )Npk_fieldTr]   to_field)r}   r   r   r  r0   rF   r,   r7   r   Zverbose_namer   r   rQ   r*   rL   r<   r   r   	get_fieldr1   r  r4   r  r   )rp   r;   r   r0   rn   r  r   r@   rA   r     s*   
	

zBaseInlineFormSet.add_fieldsc                    s    fdd|D }t  |S )Nc                    s   g | ]
}| j jkr|qS r@   )r  r0   r   r   r@   rA   r[     s    z>BaseInlineFormSet.get_unique_error_message.<locals>.<listcomp>)r}   r   r   r   r   rA   r     s   z*BaseInlineFormSet.get_unique_error_message)NNNFNNr   )re   rt   ru   r  rr   r   r   classmethodr  r   r   r   r   r@   r@   r   rA   r%   >  s     
'r%   c                    sL  ddl m  |j}rgfdd|jD }t|dkrY|d }g jjR t| rM|jjjj	r;|jjjj
vsM|jjjj	sW|jjkrW|jjvrWtdjjf |S |setd|jjf |S g jjR  fdd|jD }t|dkr|d }|S |s|rd	S td
|jjjjf td|jjjjf )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@   )r0   rX   fk_namer@   rA   r[         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 | ]#}t | r%|jjks#|jjv s#|jjjjr%|jjjjv r|qS r@   )r.   r   rQ   r*   proxyproxy_for_modelrX   )r   all_parentsparent_modelr@   rA   r[     s    
Nz'%s' has no ForeignKey to '%s'.zR'%s' has more than one ForeignKey to '%s'. You must specify a 'fk_name' attribute.)rN   r   r*   r,   r   r"  r.   r   rQ   r   r!  r   r]   )r#  rQ   r  Zcan_failr>   Zfks_to_parentr  r@   )r   r"  r  r#  rA   _get_foreign_key  sf   	


-(r$  r   c                 C   s   t | ||d}|jrd}
i d|d|d|d|d|	d|d	|d
|d|d|
d|d|d|d|d|d|d||||||d}t|fi |}||_|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   r;   ri   r
  r  r   r  r,   r=   r  r  rh   r  r  rj   rk   rl   r_   )rm   r  r	  r   r   )r$  uniquer$   r  )r#  rQ   r;   r
  r  r,   r=   r  r  r   r  ri   rh   r  rj   rk   rl   r_   r  r  rm   r  r	  r   r   r  rn   r  r@   r@   rA   r&     s^   !	
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 ur!| jrt| j | j|d< n| j j|d< d|d< t j|i | d S )Nr   Fr   )parent_instancer  r  rF   rL   r}   rr   )rp   r'  r  r  argsrn   r   r@   rA   rr   R  s   
zInlineForeignKeyField.__init__c                 C   s`   || j v r| jr
d S | jS | jrt| j| j}n| jj}t|t|kr-t| jd dd| jS )Nr&  r   )	r8   r  r'  r  rF   rL   r   r   r_   )rp   ry   origr@   r@   rA   r   ^  s   

zInlineForeignKeyField.cleanc                 C   s   dS NFr@   )rp   r   r4   r@   r@   rA   r   o  s   z!InlineForeignKeyField.has_changed)re   rt   ru   r  r   r3   r   default_error_messagesrr   r   r   r   r@   r@   r   rA   r   G  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 rs   )ry   r<   )rp   ry   r<   r@   r@   rA   rr   t  s   
z!ModelChoiceIteratorValue.__init__c                 C   
   t | jS rs   )r   ry   r   r@   r@   rA   __str__x     
z ModelChoiceIteratorValue.__str__c                 C   r.  rs   )hashry   r   r@   r@   rA   __hash__{  r0  z!ModelChoiceIteratorValue.__hash__c                 C   s   t |tr|j}| j|kS rs   )r.   r-  ry   )rp   otherr@   r@   rA   __eq__~  s   

zModelChoiceIteratorValue.__eq__N)re   rt   ru   rr   r/  r2  r4  r@   r@   r@   rA   r-  s  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 rs   )r2   rJ   r   r@   r@   rA   rr     s   zModelChoiceIterator.__init__c                 c   sJ    | j jd urd| j jfV  | j}|js| }|D ]}| |V  qd S )Nr  )r2   empty_labelrJ   Z_prefetch_related_lookupsiteratorchoice)rp   rJ   r   r@   r@   rA   __iter__  s   zModelChoiceIterator.__iter__c                 C   s    | j  | jjd urd S d S )Nr   r   )rJ   countr2   r6  r   r@   r@   rA   __len__  s    zModelChoiceIterator.__len__c                 C   s   | j jd up
| j S rs   )r2   r6  rJ   existsr   r@   r@   rA   __bool__  s   zModelChoiceIterator.__bool__c                 C   s   t | j||| j|fS rs   )r-  r2   prepare_valuelabel_from_instancerp   r   r@   r@   rA   r8    s   
zModelChoiceIterator.choiceN)re   rt   ru   rr   r9  r;  r=  r8  r@   r@   r@   rA   r5    s    
r5  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	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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)	r6  r   r3   r]   r   r^   to_field_namerS   r   c       	         K   s^   t j| f|||||d| |r|d ust| jtr!|
s!d | _n|| _|| _|	| _|| _d S )N)r   r3   r]   r   r^   )	r   rr   r.   r3   r   r6  rJ   rS   rA  )rp   rJ   r6  r   r3   r]   r   r^   rA  rS   r   rn   r@   r@   rA   rr     s*   	

zModelChoiceField.__init__c                 C   s   t  }||S rs   r   )rp   ry   Znon_null_character_validatorr@   r@   rA   validate_no_null_characters  s   z,ModelChoiceField.validate_no_null_charactersc                 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.
        )rf   rS   r   r@   r@   rA   rK     s   
z%ModelChoiceField.get_limit_choices_toc                    s*   t t| |}| jd ur| j |_|S rs   )r}   r
   __deepcopy__rJ   all)rp   memoresultr   r@   rA   rC    s   
zModelChoiceField.__deepcopy__c                 C   s   | j S rs   )r   r   r@   r@   rA   _get_queryset  s   zModelChoiceField._get_querysetc                 C   s$   |d u rd n|  | _| j| j_d S rs   )rD  r   choicesr3   )rp   rJ   r@   r@   rA   _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.
        r   r@  r@   r@   rA   r?    s   z$ModelChoiceField.label_from_instancec                 C   s   t | dr| jS | | S )N_choices)rO   rK  r7  r   r@   r@   rA   _get_choices  s   

	zModelChoiceField._get_choicesc                    s.   t |dr| jr|| jS |jS t |S Nr*   )rO   rA  Zserializable_valuerL   r}   r>  rp   ry   r   r@   rA   r>    s
   
zModelChoiceField.prepare_valuec              
   C   s   || j v rd S | | z| jpd}t|| jjrt||}| jjdi ||i}W |S  tt	| jjj
fyD   t| jd dd|idw )NrL   r&  ry   r   paramsr@   )r8   rB  rA  r.   rJ   rQ   rF   r7   r   rg   ZDoesNotExistr   r_   )rp   ry   keyr@   r@   rA   r     s    



zModelChoiceField.to_pythonc                 C   s   t | |S rs   )r   validaterN  r@   r@   rA   rR  %  r   zModelChoiceField.validatec                 C   s@   | j rdS |d ur|nd}|d ur|nd}t| |t|kS )NFr  )disabledr   r>  )rp   r   r4   initial_valueZ
data_valuer@   r@   rA   r   (  s
   zModelChoiceField.has_changed)re   rt   ru   r  r   r,  r5  r7  rr   rB  rK   rC  rG  rI  propertyrJ   r?  rL  r
   rH  fsetr>  r   rR  r   r   r@   r@   r   rA   r      s<    $

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 )Nr6  )r}   rr   )rp   rJ   rn   r   r@   rA   rr   =  s   z!ModelMultipleChoiceField.__init__c                 C   s   |sg S t | |S rs   )r  _check_valuesrN  r@   r@   rA   r   @  s   z"ModelMultipleChoiceField.to_pythonc                 C   sr   |  |}| jr|st| jd dd| js|s| j S t|ttfs-t| jd dd| 	|}| 
| |S )Nr   r)  rW  )r>  r   r   r_   rJ   r  r.   r  r   rY  Zrun_validators)rp   ry   r   r@   r@   rA   r   E  s   





zModelMultipleChoiceField.cleanc              
      s   | j pd zt|}W n ty   t| jd ddw |D ])}| | z| jjdi  |i W q ttfyG   t| jd dd|idw | jjdi d  |i} fdd|D }|D ]}t	||vrtt| 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.)
        rL   rW  r)  rX  rO  z%s__inc                    s   h | ]	}t t| qS r@   )r   rF   r   rQ  r@   rA   r|   r  r  z9ModelMultipleChoiceField._check_values.<locals>.<setcomp>r&  ry   Nr@   )
rA  	frozensetrg   r   r_   rB  rJ   rP   r   r   )rp   ry   rL   r   Zpksvalr@   rZ  rA   rY  V  s>   

z&ModelMultipleChoiceField._check_valuesc                    sD   t |drt|tst |dst j  fdd|D S t |S )Nr9  r*   c                    s   g | ]} |qS r@   r@   )rY   r{   r>  r@   rA   r[     r   z:ModelMultipleChoiceField.prepare_value.<locals>.<listcomp>)rO   r.   r   r}   r>  rN  r   r]  rA   r>  |  s   z&ModelMultipleChoiceField.prepare_valuec                 C   s`   | j rdS |d u rg }|d u rg }t|t|krdS dd | |D }dd |D }||kS )NFTc                 S      h | ]}t |qS r@   rJ  rY   ry   r@   r@   rA   r|     r   z7ModelMultipleChoiceField.has_changed.<locals>.<setcomp>c                 S   r^  r@   rJ  r_  r@   r@   rA   r|     r   )rS  r   r>  )rp   r   r4   Zinitial_setZdata_setr@   r@   rA   r     s   z$ModelMultipleChoiceField.has_changed)re   rt   ru   r  r   r3   r   Zhidden_widgetr   r,  rr   r   r   rY  r>  r   r   r@   r@   r   rA   r!   0  s     &
r!   c                 C   s"   t | do| jjd up| jjd uS rM  )rO   r*   r,   r=   )r`   r@   r@   rA   modelform_defines_fields  s   
r`  )NN)	NNNNNNNNNr+  )=r  	itertoolsr   Zdjango.core.exceptionsr   r   r   r   Zdjango.core.validatorsr   Zdjango.db.models.utilsr	   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.choicesr   Zdjango.utils.hashabler   Zdjango.utils.textr   r   Zdjango.utils.translationr   r   r   r(   r"   rB   r   rT   r   ro   rv   r   r   r'   r#   r$   r%   r$  r&   r   r-  r5  r    r!   r`  r@   r@   r@   rA   <module>   s    

0vI ]
[  g
G
uR
E, d