3
W­E^Ü  ã               @   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 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fd,d„Z*G d-d„ de)ƒZ+d>d.d/„Z,e'e+dddd0d+ddddd+dddddd+dfd1d„Z-G d2d3„ d3e
ƒZ.G d4d5„ d5ƒZ/G d6d„ de	ƒZ0G d7d„ de0ƒZ1d8d9„ Z2d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Ú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 }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ƒƒr´|j|jƒ| |j j
jkr´q$t||jƒrÌ|j|ƒ q$|j|||j ƒ q$W x|D ]}|j|||j ƒ qèW |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© r9   ú5/tmp/pip-build-78s3knkw/Django/django/forms/models.pyÚconstruct_instance   s,    
$
r;   c             C   sl   | j }i }x\t|j|j|jƒD ]F}t|ddƒs0q|dk	rD|j|krDq|rT|j|krTq|j| ƒ||j< qW |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)r5   r%   r6   r7   r-   r8   r9   r9   r:   r   H   s    c             C   s6   t | dƒr2t | dƒr2| jƒ }|dk	r2| jj|ƒ| _dS )z=Apply limit_choices_to to the formfield's queryset if needed.ÚquerysetÚget_limit_choices_toN)ÚhasattrrA   r@   Zcomplex_filter)Ú	formfieldÚlimit_choices_tor9   r9   r:   Ú#apply_limit_choices_to_to_formfielda   s    rE   T)Úapply_limit_choices_toc
               sü  i ‰g ‰| j }ddlm‰  ‡ fdd„|jD ƒ}�xªt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r¦qFˆr¶|j	ˆkr¶qFi }|rÖ|j	|krÖ||j	 |d	< |tksì|rô|j	|krôd
|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|ƒ�s tdƒ‚n||f|Ž}|�rÌ|
�rÀt|ƒ |ˆ|j	< qFˆj|j	ƒ qFW |�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 r9   )r'   )Ú.0r8   )Ú
ModelFieldr9   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 | ]&}ˆ  s|ˆ kr|ˆkrˆj |ƒ|“qS r9   )r0   )rG   r8   )r6   Ú
field_dictÚignoredr9   r:   ú
<dictcomp>»   s   z$fields_for_model.<locals>.<dictcomp>)r#   Zdjango.db.models.fieldsr   r=   Úsortedr   r<   r>   r?   r)   r   Ú__name__r   rC   ÚcallableÚ	TypeErrorrE   r2   )Úmodelr%   r6   ÚwidgetsÚformfield_callbackÚlocalized_fieldsÚlabelsÚ
help_textsrL   Úfield_classesrF   r7   Zsortable_private_fieldsr8   ÚkwargsrC   r9   )rH   r6   rN   rO   r:   r   i   sX    "


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 )
NrU   r%   r6   rV   rX   rY   rZ   rL   r[   )
r?   rU   r%   r6   rV   rX   rY   rZ   rL   r[   )ÚselfÚoptionsr9   r9   r:   Ú__init__Ã   s    zModelFormOptions.__init__)N)rR   Ú
__module__Ú__qualname__r`   r9   r9   r9   r:   r]   Â   s   r]   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 ƒƒ }|_
xBdD ]:}	t	||	ƒ}
t|
tƒr~|
tkr~d|j|	|
dœ }t|ƒ‚q~W |j�rx|jd krä|jd krätd| ƒ‚|jtkrôd |_t|j|j|j|j||j|j|j|j|jd	d
�}dd„ |jƒ D ƒ}|j|jƒ}|�rjd}|dj|ƒ|jjf }t|ƒ‚|j |jƒ n|j}||_!|S )NÚMetarW   r%   r6   rX   zP%(model)s.Meta.%(opt)s cannot be a string. Did you mean to type: ('%(value)s',)?)rU   ÚoptÚvaluez|Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form %s needs updating.F)rF   c             S   s   h | ]\}}|s|’qS r9   r9   )rG   ÚkÚvr9   r9   r:   ú	<setcomp>  s    z-ModelFormMetaclass.__new__.<locals>.<setcomp>z&Unknown field(s) (%s) specified for %sz, )r%   r6   rX   )"rB   rd   rW   ÚpopÚsuperrc   Ú__new__r   r]   r?   r#   r'   Ústrr   rR   rT   rU   r%   r6   r   r   rV   rX   rY   rZ   rL   r[   ÚitemsÚ
differenceZdeclared_fieldsÚjoinr   ÚupdateZbase_fields)Zmcsr)   ÚbasesÚattrsZbase_formfield_callbackÚbrW   Ú	new_classr7   re   rf   Úmsgr%   Znone_model_fieldsZmissing_fieldsÚmessage)Ú	__class__r9   r:   rl   Ð   sR    







zModelFormMetaclass.__new__)rR   ra   rb   rl   Ú__classcell__r9   r9   )rx   r:   rc   Ï   s   rc   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   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	ƒ j
|||||||||
|d�
 x| jjƒ D ]}t|ƒ qŠW d S )Nz'ModelForm has no model class specified.F)Úuse_required_attributeÚrenderer)r#   rU   Ú
ValueErrorr5   r   r%   r6   rq   Ú_validate_uniquerk   r`   ÚvaluesrE   )r^   r-   r.   Úauto_idÚprefixÚinitialÚerror_classZlabel_suffixZempty_permittedr5   rz   r{   r7   Zobject_datarC   )rx   r9   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krŽ|j|jƒ q| j| }| jj|ƒ}|j	 r|j
 r||jkr|j|jƒ qW |S )z‘
        For backwards-compatibility, exclude several types of fields from model
        validation. See tickets #12507, #12521, #12553.
        )r5   r#   r%   r)   r2   r6   Ú_errorsr$   r0   ZblankÚrequiredr1   )r^   r6   r8   r+   Z
form_fieldZfield_valuer9   r9   r:   Ú_get_validation_exclusions5  s     

	
z(BaseModelForm._get_validation_exclusionsc             C   s   d| _ | jS )NT)r}   r$   )r^   r9   r9   r:   Úclean^  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#   rB   r‡   r   rn   rL   r%   r'   r   Úcoderw   Z	add_error)r^   Úerrorsr7   r‡   r+   ÚmessagesrL   rw   r9   r9   r:   Ú_update_errorsb  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)r6   Úvalidate_unique)r#   r…   r%   rn   r'   ÚInlineForeignKeyFieldr2   r;   r5   r6   r   r‹   Z
full_cleanr}   rŒ   )r^   r7   r6   r)   r+   Úer9   r9   r:   Ú_post_clean~  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‚
        Call the instance's validate_unique() method and update the form's
        validation errors if any were raised.
        )r6   N)r…   r5   rŒ   r   r‹   )r^   r6   rŽ   r9   r9   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.
        r3   N)r$   r#   r6   r%   r5   r   r>   r=   rB   r)   r3   )r^   r$   r6   r%   r7   r8   r9   r9   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|   r5   r#   Zobject_nameÚ_stateÚaddingÚsaver�   Úsave_m2m)r^   Úcommitr9   r9   r:   r•   ¼  s    

zBaseModelForm.save)T)rR   ra   rb   r   r`   r…   r†   r‹   r�   rŒ   r�   r•   Úalters_datary   r9   r9   )rx   r:   r     s   )
c               @   s   e Zd ZdS )r   N)rR   ra   rb   r9   r9   r9   r:   r   Ö  s   )Ú	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f }td||ƒ}|r¸t|ƒ|_| jd }||dœ}t|ddƒdkrôt|ddƒdkrôt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.
    rU   Nr%   r6   rV   rX   rY   rZ   rL   r[   rd   ZForm)rd   rW   zZCalling modelform_factory without defining 'fields' or 'exclude' explicitly is prohibited.)rB   rd   ÚtypeÚstaticmethodrW   rR   r?   r   )rU   r4   r%   r6   rW   rV   rX   rY   rZ   rL   r[   rs   rr   rd   Ú
class_nameZform_class_attrsr9   r9   r:   r    Ú  s:    '

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.
    Núid_%s)r�   c               s,   || _ || _tƒ jf ||||dœ|–Ž d S )N)r-   r.   r   r€   )r@   Úinitial_extrark   r`   )r^   r-   r.   r   r€   r@   r�   r\   )rx   r9   r:   r`   8  s    zBaseModelFormSet.__init__c                s   | j st| jƒ ƒS tƒ jƒ S )z=Return the number of forms that are required in this FormSet.)Úis_boundÚlenÚget_querysetrk   Úinitial_form_count)r^   )rx   r9   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 r9   )Úpk)rG   Úor9   r9   r:   rP   F  s    z5BaseModelFormSet._existing_object.<locals>.<dictcomp>)rB   r¡   r£   r0   )r^   r¤   r9   r9   r:   Ú_existing_objectD  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^   r+   r9   r9   r:   Ú_get_to_pythonI  s    zBaseModelFormSet._get_to_pythonc                s  || j ƒ k }|r¨| jr–d| j|ƒ| jjjjf }y| j| }W n tk
rR   Y q¦X | j	| jjjƒ}y||ƒ}W n t
k
r„   Y q¦X | j|ƒ|d< qÞ| jƒ | |d< n6| jrÞy| j|| j ƒ   |d< W n tk
rÜ   Y nX tƒ j|f|Ž}|�rd|j| jjjj _|S )Nz%s-%sr5   r�   T)r¢   rŸ   r/   rU   r#   r¤   r)   r-   ÚKeyErrorr©   r   r¦   r¡   rž   Ú
IndexErrorrk   Ú_construct_formr%   r„   )r^   Úir\   Zpk_requiredZpk_keyr¤   r¨   r4   )rx   r9   r:   r¬   R  s0    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)rB   r@   rU   Ú_default_managerr¡   ÚorderedZorder_byr#   r¤   r)   r®   )r^   Úqsr9   r9   r:   r¡   t  s    

zBaseModelFormSet.get_querysetTc             C   s   |j |d�S )z8Save and return a new model instance for the given form.)r—   )r•   )r^   r4   r—   r9   r9   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•   )r^   r4   r5   r—   r9   r9   r:   Úsave_existing‹  s    zBaseModelFormSet.save_existingc             C   s   |r|j ƒ  dS )z#Deletes an existing model instance.N)Údelete)r^   Úobjr—   r9   r9   r:   Údelete_existing�  s    z BaseModelFormSet.delete_existingc                s0   |sg ˆ _ ‡ fdd„}|ˆ _ˆ j|ƒˆ j|ƒ S )zŒ
        Save model instances for every form, adding and changing instances
        as necessary, and return the list of instances.
        c                 s   xˆ j D ]} | jƒ  qW d S )N)Úsaved_formsr–   )r4   )r^   r9   r:   r–   œ  s    z'BaseModelFormSet.save.<locals>.save_m2m)r·   r–   Úsave_existing_objectsÚsave_new_objects)r^   r—   r–   r9   )r^   r:   r•   ”  s
    zBaseModelFormSet.savec             C   s   | j ƒ  d S )N)rŒ   )r^   r9   r9   r:   r†   ¤  s    zBaseModelFormSet.cleanc                s  t ƒ }t ƒ }ˆj‰‡fdd„ˆjD ƒ}x:|D ]2‰ ˆ jƒ }ˆ jj|d�\}}|j|ƒ |j|ƒ q,W g }x°|D ]¨\}}	t ƒ }
x˜|D ]�‰ ‡ ‡fdd„|	D ƒ}tdd„ |D ƒƒ}|o´d |kr€||
k�r|jˆj	|	ƒƒ ˆj
ˆjƒ gƒˆ jt< x|	D ]}|ˆ jkrìˆ j|= qìW |
j|ƒ q€W qlW xâ|D ]Ú}t ƒ }
|\}}}}xÀ|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ˆj|ƒƒ ˆj
ˆjƒ gƒˆ jt< ˆ j|= |
j|ƒ �q:W �qW |�r
t|ƒ‚d S )Nc                s    g | ]}|j ƒ r|ˆ kr|‘qS r9   )Zis_valid)rG   r4   )Úforms_to_deleter9   r:   rI   ¬  s    z4BaseModelFormSet.validate_unique.<locals>.<listcomp>)r6   c             3   s0   | ](}|ˆ j kr|ˆjkr|nˆ j | V  qd S )N)r$   Úunique_fields)rG   r+   )r4   r^   r9   r:   ú	<genexpr>º  s   z3BaseModelFormSet.validate_unique.<locals>.<genexpr>c             s   s6   | ].}t |d ƒr|jƒ nt|tƒr*t|ƒn|V  qdS )Ú_get_pk_valN)rB   r½   r'   ÚlistÚtuple)rG   Údr9   r9   r:   r¼   ¿  s   Údate)ÚsetÚdeleted_formsZformsr…   r5   Z_get_unique_checksrq   r¿   r2   Úget_unique_error_messager‚   Úget_form_errorrƒ   r   r$   ÚaddÚyearÚmonthÚdayr?   Úget_date_error_messager   )r^   Zall_unique_checksZall_date_checksZvalid_formsr6   Zunique_checksZdate_checksr‰   ZuclassÚunique_checkZ	seen_dataZrow_datar+   Ú
date_checkÚlookupZ
unique_forrÁ   Z	date_datar-   r9   )r4   rº   r^   r:   rŒ   §  sX    











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   Ú_)r^   rË   r9   r9   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   rm   )r^   rÌ   r9   r9   r:   rÊ   ú  s
    z'BaseModelFormSet.get_date_error_messagec             C   s   t dƒS )Nz*Please correct the duplicate values below.)r   )r^   r9   r9   r:   rÅ     s    zBaseModelFormSet.get_form_errorc             C   sª   g | _ g | _| jsg S g }| j}x„| jD ]z}|j}|jd kr>q(||krb| 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Ã   r5   r¤   r2   r¶   Úhas_changedZchanged_datar³   r·   )r^   r—   Zsaved_instancesrº   r4   rµ   r9   r9   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_formr2   r²   r·   )r^   r—   r4   r9   r9   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:y |dk	r€| jƒ | j}nd}W n tk
rž   d}Y nX t|||fƒ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ƒ 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_linkrU   r#   r¤   )r¤   )r(   Úpk_is_not_editabler9   r:   rØ   9  s    z7BaseModelFormSet.add_fields.<locals>.pk_is_not_editableNF)r�   r„   r,   )Údjango.db.modelsr(   rÖ   r×   rU   r#   r¤   Ú	_pk_fieldr)   r%   rŸ   r5   r“   r”   r¡   r«   r'   r§   r¯   ZusingÚdbrV   r0   r   r   rk   Ú
add_fields)	r^   r4   ÚindexrÖ   r×   r¤   Zpk_valuer±   r,   )rx   )r(   rØ   r:   rÜ   /  s*    
zBaseModelFormSet.add_fields)NNr�   NN)T)T)T)T)T)T)rR   ra   rb   Ú__doc__rU   rÂ   r»   r`   r¢   r¦   r©   r¬   r¡   r²   r³   r¶   r•   r˜   r†   rŒ   rÄ   rÊ   rÅ   r¸   r¹   rÜ   ry   r9   r9   )rx   r:   r   /  s.    	"



I



rÎ   Fc             C   sv   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.rd   Nr%   r6   z]Calling modelformset_factory without defining 'fields' or 'exclude' explicitly is prohibited.)
r4   r%   r6   rW   rV   rX   rY   rZ   rL   r[   )ÚextraÚmin_numÚmax_numÚ	can_orderrÕ   Úvalidate_minÚvalidate_max)r?   r   r    r   rU   )rU   r4   rW   Úformsetrß   rÕ   râ   rá   r%   r6   rV   rä   rX   rY   rZ   rL   rà   rã   r[   ÚmetaÚFormSetr9   r9   r:   r   [  s    


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jƒ | _n|| _|| _|d kr4| jj}| jjd k	rX|jf | j j| jiŽ}n|j	ƒ }| j jh| _
tƒ j||f||dœ|—Ž | jjjrÜ| j j| jjjkrÜt| jjjtƒrÈt| jjjƒ| jj_| jjjj| j jƒ d S )N)r€   r@   )Úfkr§   rU   r5   Úsave_as_newr¯   r¤   Úfilterr)   Únoner»   rk   r`   r4   r#   r%   r'   r¿   r¾   r2   )	r^   r-   r.   r5   ré   r€   r@   r\   r±   )rx   r9   r:   r`   z  s    zBaseInlineFormSet.__init__c                s   | j r
dS tƒ jƒ S )Nr   )ré   rk   r¢   )r^   )rx   r9   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jƒ< d |j|j| j	jƒ< |d k	rl||j_| j
j}| j	jj| j	jjjjjkr¬t| j
| j	jjƒ}t|d|ƒ}t|j
| j	jƒ |ƒ |S )NÚ_mutableTr¤   )rk   r¬   ré   r?   r-   rì   r/   rÚ   r)   rè   r5   r¤   r§   rÓ   rU   r#   ÚsetattrZget_attname)r^   r­   r\   r4   ZmutableZfk_value)rx   r9   r:   r¬   –  s    z!BaseInlineFormSet._construct_formc             C   s   | j jj| jd�jddƒS )N)rU   ú+Ú )rè   r§   Zget_accessor_namerU   Úreplace)Úclsr9   r9   r:   Úget_default_prefix­  s    z$BaseInlineFormSet.get_default_prefixTc                s$   t |j| jj| jƒ tƒ j||d�S )N)r—   )rí   r5   rè   r)   rk   r²   )r^   r4   r—   )rx   r9   r:   r²   ±  s    zBaseInlineFormSet.save_newc                sâ   t ƒ j||ƒ | j| jkr,| jj}ddi}n(| 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ƒ rÊt| j|jd ƒ t| jf|Ž|j|< d S )NÚpk_fieldTrJ   Úto_field)rk   rÜ   rÚ   rè   r)   r?   r%   r0   r   Zverbose_namer§   rÓ   rU   r#   r¤   r5   r“   r”   Ú	get_fieldr*   rí   Zattnamer�   )r^   r4   rÝ   r)   r\   rô   )rx   r9   r:   rÜ   ¸  s    
 

zBaseInlineFormSet.add_fieldsc                s   ‡ fdd„|D ƒ}t ƒ j|ƒS )Nc                s   g | ]}|ˆ j jkr|‘qS r9   )rè   r)   )rG   r+   )r^   r9   r:   rI   Ø  s    z>BaseInlineFormSet.get_unique_error_message.<locals>.<listcomp>)rk   rÄ   )r^   rË   )rx   )r^   r:   rÄ   ×  s    z*BaseInlineFormSet.get_unique_error_message)NNNFNN)T)rR   ra   rb   rÞ   r`   r¢   r¬   Úclassmethodrò   r²   rÜ   rÄ   ry   r9   r9   )rx   r:   r   x  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r–t	dˆˆjj
f ƒ‚n|s–t	d|jj
ˆf ƒ‚nj‡ ‡fdd„|jD ƒ}t|ƒdkrÄ|d }n>|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 r9   )r)   )rG   r8   )Úfk_namer9   r:   rI   è  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 r9   )r'   r§   rU   r#   Úget_parent_list)rG   r8   )r×   Úparent_modelr9   r:   rI   ø  s    
Nz'%s' has no ForeignKey to '%s'.z*'%s' has more than one ForeignKey to '%s'.)rÙ   r×   r#   r%   r    r'   r§   rU   rø   r|   rJ   )rù   rU   r÷   Zcan_failr7   Zfks_to_parentrè   r9   )r×   r÷   rù   r:   Ú_get_foreign_keyÜ  s:    	
rú   rÒ   c             C   sX   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Î   )r4   rW   rå   rß   rÕ   râ   r%   r6   rà   rá   rV   rã   rä   rX   rY   rZ   rL   r[   )rú   Úuniquer   rè   )rù   rU   r4   rå   r÷   r%   r6   rß   râ   rÕ   rá   rW   rV   rä   rX   rY   rZ   rL   rà   rã   r[   rè   r\   rç   r9   r9   r:   r     s0    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?   r¤   rk   r`   )r^   rý   ró   rô   Úargsr\   )rx   r9   r:   r`   I  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ˆ   )	r1   ró   rý   rô   r?   r¤   rm   r   rL   )r^   rf   Úorigr9   r9   r:   r†   U  s    
zInlineForeignKeyField.cleanc             C   s   dS )NFr9   )r^   r�   r-   r9   r9   r:   rÔ   d  s    z!InlineForeignKeyField.has_changed)rR   ra   rb   rÞ   r   r,   rÐ   Údefault_error_messagesr`   r†   rÔ   ry   r9   r9   )rx   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 )N)r+   r@   )r^   r+   r9   r9   r:   r`   i  s    zModelChoiceIterator.__init__c             c   sL   | j jd k	rd| j jfV  | j}|js.|jƒ }x|D ]}| j|ƒV  q4W d S )Nrï   )r+   Úempty_labelr@   Z_prefetch_related_lookupsÚiteratorÚchoice)r^   r@   rµ   r9   r9   r:   Ú__iter__m  s    
zModelChoiceIterator.__iter__c             C   s   | j jƒ | jjd k	rdnd S )NrÎ   r   )r@   Úcountr+   r  )r^   r9   r9   r:   Ú__len__w  s    zModelChoiceIterator.__len__c             C   s   | j jd k	p| jjƒ S )N)r+   r  r@   Úexists)r^   r9   r9   r:   Ú__bool__}  s    zModelChoiceIterator.__bool__c             C   s   | j j|ƒ| j j|ƒfS )N)r+   Úprepare_valueÚlabel_from_instance)r^   rµ   r9   r9   r:   r  €  s    zModelChoiceIterator.choiceN)rR   ra   rb   r`   r  r  r	  r  r9   r9   r9   r:   r  h  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
„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ï   )r  r„   r,   rJ   r�   rK   Úto_field_namerD   c            K   sN   |r|d k	rd | _ n|| _ tj| f|||||dœ|
—Ž || _|	| _|| _d S )N)r„   r,   rJ   r�   rK   )r  r   r`   r@   rD   r  )r^   r@   r  r„   r,   rJ   r�   rK   r  rD   r\   r9   r9   r:   r`   Ž  s    
zModelChoiceField.__init__c             C   s   t | jƒr| jƒ S | jS )z�
        Return ``limit_choices_to`` for this form field.

        If it is a callable, invoke it and return the result.
        )rS   rD   )r^   r9   r9   r:   rA   ¡  s    
z%ModelChoiceField.get_limit_choices_toc                s*   t t| ƒj|ƒ}| jd k	r&| jjƒ |_|S )N)rk   r   Ú__deepcopy__r@   Úall)r^   ÚmemoÚresult)rx   r9   r:   r  «  s    
zModelChoiceField.__deepcopy__c             C   s   | j S )N)r®   )r^   r9   r9   r:   Ú_get_queryset²  s    zModelChoiceField._get_querysetc             C   s$   |d krd n|j ƒ | _| j| j_d S )N)r  r®   Úchoicesr,   )r^   r@   r9   r9   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.
        )rm   )r^   rµ   r9   r9   r:   r  ½  s    z$ModelChoiceField.label_from_instancec             C   s   t | dƒr| jS | j| ƒS )NÚ_choices)rB   r  r  )r^   r9   r9   r:   Ú_get_choicesÅ  s    
	zModelChoiceField._get_choicesc                s.   t |dƒr"| jr|j| jƒS |jS tƒ j|ƒS )Nr#   )rB   r  Zserializable_valuer¤   rk   r
  )r^   rf   )rx   r9   r:   r
  Ö  s
    
zModelChoiceField.prepare_valuec             C   s~   || j krd S y8| jpd}t|| jjƒr2t||ƒ}| jjf ||iŽ}W n2 tt| jjj	fk
rx   t
| jd dd�‚Y nX |S )Nr¤   rü   )rˆ   )r1   r  r'   r@   rU   r?   r0   r|   rT   ZDoesNotExistr   rL   )r^   rf   Úkeyr9   r9   r:   r¨   Þ  s    


zModelChoiceField.to_pythonc             C   s   t j| |ƒS )N)r   Úvalidate)r^   rf   r9   r9   r:   r  ê  s    zModelChoiceField.validatec             C   s@   | j r
dS |d k	r|nd}|d k	r&|nd}t| j|ƒƒt|ƒkS )NFrï   )Údisabledrm   r
  )r^   r�   r-   Úinitial_valueZ
data_valuer9   r9   r:   rÔ   í  s
    zModelChoiceField.has_changed)rR   ra   rb   rÞ   rÐ   r   r  r  r`   rA   r  r  r  Úpropertyr@   r  r  r   Z_set_choicesr  r
  r¨   r  rÔ   ry   r9   r9   )rx   r:   r   „  s$   

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.)r¾   rü   Úinvalid_pk_valuec                s   t ƒ j|fdd i|—Ž d S )Nr  )rk   r`   )r^   r@   r\   )rx   r9   r:   r`      s    z!ModelMultipleChoiceField.__init__c             C   s   |sg S t | j|ƒƒS )N)r¾   Ú_check_values)r^   rf   r9   r9   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   rL   r@   rë   r'   r¾   r¿   r  Zrun_validators)r^   rf   r±   r9   r9   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Ž}‡ fdd„|D ƒ}x0|D ](}t|ƒ|krÂt| jd	 d	d
|id�‚qÂW |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.)
        r¤   r¾   )rˆ   r  )rˆ   Úparamsz%s__inc                s   h | ]}t t|ˆ ƒƒ’qS r9   )rm   r?   )rG   r¥   )r  r9   r:   ri   1  s    z9ModelMultipleChoiceField._check_values.<locals>.<setcomp>rü   rf   )	r  Ú	frozensetrT   r   rL   r@   rê   r|   rm   )r^   rf   r¤   r±   ZpksÚvalr9   )r  r:   r    s0    


z&ModelMultipleChoiceField._check_valuesc                sH   t |dƒr<t|tƒ r<t |dƒ r<tƒ j‰ ‡ fdd„|D ƒS tƒ j|ƒS )Nr  r#   c                s   g | ]}ˆ |ƒ‘qS r9   r9   )rG   rh   )r
  r9   r:   rI   @  s    z:ModelMultipleChoiceField.prepare_value.<locals>.<listcomp>)rB   r'   rm   rk   r
  )r^   rf   )rx   )r
  r:   r
  ;  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„ | j|ƒD ƒ}dd„ |D ƒ}||kS )NFTc             S   s   h | ]}t |ƒ’qS r9   )rm   )rG   rf   r9   r9   r:   ri   L  s    z7ModelMultipleChoiceField.has_changed.<locals>.<setcomp>c             S   s   h | ]}t |ƒ’qS r9   )rm   )rG   rf   r9   r9   r:   ri   M  s    )r  r    r
  )r^   r�   r-   Zinitial_setZdata_setr9   r9   r:   rÔ   C  s    z$ModelMultipleChoiceField.has_changed)rR   ra   rb   rÞ   r   r,   r   Zhidden_widgetrÐ   r   r`   r¨   r†   r  r
  rÔ   ry   r9   r9   )rx   r:   r   õ  s   %c             C   s"   t | dƒo | jjd k	p | jjd k	S )Nr#   )rB   r#   r%   r6   )rM   r9   r9   r:   Úmodelform_defines_fieldsQ  s    
r   )r   r   r   r   r   r   r   r   r   r   r   r    )NN)NN)	NNNNNNNNN)NF)3rÞ   Ú	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.utils.textr   r   Zdjango.utils.translationr   r   rÐ   r!   r   r;   r   rE   r   r]   rc   r   r   r    r   r   r   rú   r   r�   r  r   r   r   r9   r9   r9   r:   Ú<module>   sj      
)
   VH @R  .d
7&)q\