3
v^                 @   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rq$t||jr|j| q$|j|||j  q$W x|D ]}|j|||j  qW |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)	django.dbr"   _metacleaned_datafieldseditable
isinstance	AutoFieldnamehas_defaultfieldwidgetvalue_omitted_from_datadatafiles
add_prefixgetempty_values	FileFieldappendsave_form_data)	forminstancer&   excluder"   optsr%   Zfile_field_listf r<   7/usr/lib/python3.6/site-packages/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*   value_from_object)r8   r&   r9   r:   r/   r;   r<   r<   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)hasattrrE   rD   complex_filter)	formfieldlimit_choices_tor<   r<   r=   #apply_limit_choices_to_to_formfielda   s    rJ   T)apply_limit_choices_toc
               s  i g | j }ddlm   fdd|jD }xtt|j||jD ]}t|dds|dk	rF|j	|krFdks||j	krFt
d|j	| jf qF|dk	r|j	|krqFr|j	krqFi }|r|j	|kr||j	 |d	< |tks|r|j	|krd
|d< |r|j	|kr||j	 |d< |r4|j	|kr4||j	 |d< |rT|j	|krT||j	 |d< |	rt|j	|	krt|	|j	 |d< |dkr|jf |}n t|stdn||f|}|r|
rt| ||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 r<   )r(   ).0r;   )
ModelFieldr<   r=   
<listcomp>   s    z$fields_for_model.<locals>.<listcomp>r'   FNzH'%s' cannot be specified for %s model form as it is a non-editable fieldr-   T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 r<   )r2   )rL   r;   )r9   
field_dictignoredr<   r=   
<dictcomp>   s   z$fields_for_model.<locals>.<dictcomp>)r$   django.db.models.fieldsr   r@   sortedr   r?   rA   rB   r*   r   __name__r   rH   callable	TypeErrorrJ   r5   )modelr&   r9   widgetsformfield_callbacklocalized_fieldslabels
help_textsrR   field_classesrK   r:   Zsortable_private_fieldsr;   kwargsrH   r<   )rM   r9   rT   rU   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 )
Nr\   r&   r9   r]   r_   r`   ra   rR   rb   )
rB   r\   r&   r9   r]   r_   r`   ra   rR   rb   )selfoptionsr<   r<   r=   __init__   s    zModelFormOptions.__init__)N)rY   
__module____qualname__rg   r<   r<   r<   r=   rd      s   rd   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rtd| |jtkrd |_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Metar^   r&   r9   r_   zP%(model)s.Meta.%(opt)s cannot be a string. Did you mean to type: ('%(value)s',)?)r\   optvaluez|Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited; form %s needs updating.F)rK   c             S   s   h | ]\}}|s|qS r<   r<   )rL   kvr<   r<   r=   	<setcomp>  s    z-ModelFormMetaclass.__new__.<locals>.<setcomp>z&Unknown field(s) (%s) specified for %sz, )r&   r9   r_   )"rF   rk   r^   popsuperrj   __new__r   rd   rB   r$   r(   strr   rY   r[   r\   r&   r9   r   r   r]   r_   r`   ra   rR   rb   items
differencedeclared_fieldsjoinr   updatebase_fields)mcsr*   basesattrsZbase_formfield_callbackbr^   	new_classr:   rl   rm   msgr&   Znone_model_fieldsZmissing_fieldsmessage)	__class__r<   r=   rs      sR    







zModelFormMetaclass.__new__)rY   rh   ri   rs   __classcell__r<   r<   )r   r=   rj      s   rj   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| qW d S )Nz'ModelForm has no model class specified.F)use_required_attributerenderer)r$   r\   
ValueErrorr8   r   r&   r9   ry   _validate_uniquerr   rg   valuesrJ   )re   r/   r0   auto_idprefixinitialerror_classlabel_suffixempty_permittedr8   r   r   r:   Zobject_datarH   )r   r<   r=   rg     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.
        )r8   r$   r&   r*   r5   r9   _errorsr%   r2   blankrequiredr3   )re   r9   r;   r,   Z
form_fieldfield_valuer<   r<   r=   _get_validation_exclusions5  s     

	
z(BaseModelForm._get_validation_exclusionsc             C   s   d| _ | jS )NT)r   r%   )re   r<   r<   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$   rF   r   r   ru   rR   r&   r(   r   coder   	add_error)re   errorsr:   r   r,   messagesrR   r   r<   r<   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)r9   validate_unique)r$   r   r&   ru   r(   InlineForeignKeyFieldr5   r>   r8   r9   r   r   
full_cleanr   r   )re   r:   r9   r*   r,   er<   r<   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.
        )r9   N)r   r8   r   r   r   )re   r9   r   r<   r<   r=   r     s
    zBaseModelForm.validate_uniquec             C   s   | j }| jj}| jj}| jj}x`t|j|jD ]N}t|ds>q.|rN|j	|krNq.|r^|j	|kr^q.|j	|kr.|j
| j||j	  q.W dS )zS
        Save the many-to-many fields and generic relations for this form.
        r6   N)r%   r$   r9   r&   r8   r   rA   r@   rF   r*   r6   )re   r%   r9   r&   r:   r;   r<   r<   r=   	_save_m2m  s    

zBaseModelForm._save_m2mTc             C   sP   | j r*td| jjj| jjjr dndf |rB| jj  | j  n| j| _	| jS )z
        Save this form's self.instance object if commit=True. Otherwise, add
        a save_m2m() method to the form which can be called after the instance
        is saved manually at a later time. Return the model instance.
        z8The %s could not be %s because the data didn't validate.createdchanged)
r   r   r8   r$   object_name_stateaddingsaver   save_m2m)re   commitr<   r<   r=   r     s    

zBaseModelForm.save)T)rY   rh   ri   r   rg   r   r   r   r   r   r   r   alters_datar   r<   r<   )r   r=   r     s   )
c               @   s   e Zd ZdS )r   N)rY   rh   ri   r<   r<   r<   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||}|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.
    r\   Nr&   r9   r]   r_   r`   ra   rR   rb   rk   Form)rk   r^   zZCalling modelform_factory without defining 'fields' or 'exclude' explicitly is prohibited.)rF   rk   typestaticmethodr^   rY   rB   r   )r\   r7   r&   r9   r^   r]   r_   r`   ra   rR   rb   r}   r|   rk   
class_nameZform_class_attrsr<   r<   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/   r0   r   r   )rD   initial_extrarr   rg   )re   r/   r0   r   r   rD   r   rc   )r   r<   r=   rg   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_querysetrr   initial_form_count)re   )r   r<   r=   r   >  s    z#BaseModelFormSet.initial_form_countc             C   s*   t | dsdd | j D | _| jj|S )N_object_dictc             S   s   i | ]}||j qS r<   )pk)rL   or<   r<   r=   rV   F  s    z5BaseModelFormSet._existing_object.<locals>.<dictcomp>)rF   r   r   r2   )re   r   r<   r<   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_fieldget_related_field	to_python)re   r,   r<   r<   r=   _get_to_pythonI  s    zBaseModelFormSet._get_to_pythonc                s  || j  k }|r| jrd| j|| jjjjf }y| j| }W n tk
rR   Y qX | j	| jjj}y||}W n t
k
r   Y qX | j||d< q| j | |d< n6| jry| j|| j    |d< W n tk
r   Y nX t j|f|}|rd|j| jjjj _|S )Nz%s-%sr8   r   T)r   r   r1   r\   r$   r   r*   r/   KeyErrorr   r   r   r   r   
IndexErrorrr   _construct_formr&   r   )re   irc   Zpk_requiredZpk_keyr   r   r7   )r   r<   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)rF   rD   r\   _default_managerr   Zorderedorder_byr$   r   r*   r   )re   qsr<   r<   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   )re   r7   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   )re   r7   r8   r   r<   r<   r=   save_existing  s    zBaseModelFormSet.save_existingc             C   s   |r|j   dS )z#Deletes an existing model instance.N)delete)re   objr   r<   r<   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   )r7   )re   r<   r=   r     s    z'BaseModelFormSet.save.<locals>.save_m2m)r   r   save_existing_objectssave_new_objects)re   r   r   r<   )re   r=   r     s
    zBaseModelFormSet.savec             C   s   | j   d S )N)r   )re   r<   r<   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 }|od |kr||
kr|jj	|	 j
j g jt< x|	D ]}| jkr j|= qW |
j| qW 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 r<   )is_valid)rL   r7   )forms_to_deleter<   r=   rN     s    z4BaseModelFormSet.validate_unique.<locals>.<listcomp>)r9   c             3   s0   | ](}| j kr|jkr|n j | V  qd S )N)r%   unique_fields)rL   r,   )r7   re   r<   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)rF   r   r(   listtuple)rL   dr<   r<   r=   r     s   date)setdeleted_formsformsr   r8   Z_get_unique_checksry   r   r5   get_unique_error_messager   get_form_errorr   r   r%   addyearmonthdayrB   get_date_error_messager   )re   Zall_unique_checksZall_date_checksZvalid_formsr9   Zunique_checksZdate_checksr   Zuclassunique_checkZ	seen_dataZrow_datar,   
date_checklookupZ
unique_forr   Z	date_datar/   r<   )r7   r   re   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   _)re   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   rt   )re   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   )re   r<   r<   r=   r     s    zBaseModelFormSet.get_form_errorc             C   s   g | _ g | _| jsg S g }| j}x| jD ]z}|j}|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_objectsinitial_formsr   r8   r   r5   r   has_changedchanged_datar   r   )re   r   Zsaved_instancesr   r7   r   r<   r<   r=   r     s&    
z&BaseModelFormSet.save_existing_objectsc             C   s^   g | _ xP| jD ]F}|j sq| jr.| j|r.q| j j| j||d |s| jj| qW | j S )N)r   )Znew_objectsextra_formsr   
can_delete_should_delete_formr5   r   r   )re   r   r7   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: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'   auto_createdr(   r   parent_linkr\   r$   r   )r   )r)   pk_is_not_editabler<   r=   r   9  s    z7BaseModelFormSet.add_fields.<locals>.pk_is_not_editableNF)r   r   r-   )django.db.modelsr)   r   r   r\   r$   r   	_pk_fieldr*   r&   r   r8   r   r   r   r   r(   r   r   usingdbr]   r2   r   r   rr   
add_fields)	re   r7   indexr   r   r   Zpk_valuer   r-   )r   )r)   r   r=   r   /  s*    
zBaseModelFormSet.add_fields)NNr   NN)T)T)T)T)T)T)rY   rh   ri   __doc__r\   r   r   rg   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r<   r<   )r   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.rk   Nr&   r9   z]Calling modelformset_factory without defining 'fields' or 'exclude' explicitly is prohibited.)
r7   r&   r9   r^   r]   r_   r`   ra   rR   rb   )extramin_nummax_num	can_orderr   validate_minvalidate_max)rB   r   r    r   r\   )r\   r7   r^   formsetr   r   r   r   r&   r9   r]   r   r_   r`   ra   rR   r   r   rb   metaFormSetr<   r<   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rt| jjjtrt| jjj| jj_| jjjj| j j d S )N)r   rD   )fkr   r\   r8   save_as_newr   r   filterr*   noner   rr   rg   r7   r$   r&   r(   r   r   r5   )	re   r/   r0   r8   r  r   rD   rc   r   )r   r<   r=   rg   z  s    zBaseInlineFormSet.__init__c                s   | j r
dS t j S )Nr   )r  rr   r   )re   )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j< d |j|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	j | |S )N_mutableTr   )rr   r   r  rB   r/   r  r1   r   r*   r  r8   r   r   r   r\   r$   setattrget_attname)re   r   rc   r7   mutableZfk_value)r   r<   r=   r     s    z!BaseInlineFormSet._construct_formc             C   s   | j jj| jdjddS )N)r\   + )r  r   Zget_accessor_namer\   replace)clsr<   r<   r=   get_default_prefix  s    z$BaseInlineFormSet.get_default_prefixTc                s$   t |j| jj| j t j||dS )N)r   )r	  r8   r  r*   rr   r   )re   r7   r   )r   r<   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 rt| j|jd  t| jf||j|< d S )Npk_fieldTrP   to_field)rr   r   r   r  r*   rB   r&   r2   r   verbose_namer   r   r\   r$   r   r8   r   r   	get_fieldr+   r	  attnamer   )re   r7   r   r*   rc   r  )r   r<   r=   r     s    
 

zBaseInlineFormSet.add_fieldsc                s    fdd|D }t  j|S )Nc                s   g | ]}| j jkr|qS r<   )r  r*   )rL   r,   )re   r<   r=   rN     s    z>BaseInlineFormSet.get_unique_error_message.<locals>.<listcomp>)rr   r   )re   r   )r   )re   r=   r     s    z*BaseInlineFormSet.get_unique_error_message)NNNFNN)T)rY   rh   ri   r   rg   r   r   classmethodr  r   r   r   r   r<   r<   )r   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rt	djj
f n|st	d|jj
f nj fdd|jD }t|dkr|d }n>|s|rd	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*   )rL   r;   )fk_namer<   r=   rN     s    z$_get_foreign_key.<locals>.<listcomp>r   z)fk_name '%s' is not a ForeignKey to '%s'.z'%s' has no field named '%s'.c                s8   g | ]0}t | r|jjks0|jjjj kr|qS r<   )r(   r   r\   r$   get_parent_list)rL   r;   )r   parent_modelr<   r=   rN     s    
Nz'%s' has no ForeignKey to '%s'.z*'%s' has more than one ForeignKey to '%s'.)r   r   r$   r&   r   r(   r   r\   r  r   rP   )r  r\   r  Zcan_failr:   Zfks_to_parentr  r<   )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   )r7   r^   r  r   r   r   r&   r9   r   r   r]   r   r   r_   r`   ra   rR   rb   )r  uniquer   r  )r  r\   r7   r  r  r&   r9   r   r   r   r   r^   r]   r   r_   r`   ra   rR   r   r   rb   r  rc   r  r<   r<   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  rB   r   rr   rg   )re   r  r  r  argsrc   )r   r<   r=   rg   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   )	r3   r  r  r  rB   r   rt   r   rR   )re   rm   origr<   r<   r=   r   U  s    
zInlineForeignKeyField.cleanc             C   s   dS )NFr<   )re   r   r/   r<   r<   r=   r   d  s    z!InlineForeignKeyField.has_changed)rY   rh   ri   r   r   r-   r   default_error_messagesrg   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 )N)r,   rD   )re   r,   r<   r<   r=   rg   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_labelrD   Z_prefetch_related_lookupsiteratorchoice)re   rD   r   r<   r<   r=   __iter__m  s    
zModelChoiceIterator.__iter__c             C   s   | j j | jjd k	rdnd S )Nr   r   )rD   countr,   r"  )re   r<   r<   r=   __len__w  s    zModelChoiceIterator.__len__c             C   s   | j jd k	p| jj S )N)r,   r"  rD   exists)re   r<   r<   r=   __bool__}  s    zModelChoiceIterator.__bool__c             C   s   | j j|| j j|fS )N)r,   prepare_valuelabel_from_instance)re   r   r<   r<   r=   r$    s    zModelChoiceIterator.choiceN)rY   rh   ri   rg   r%  r'  r)  r$  r<   r<   r<   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-   rP   r   rQ   to_field_namerI   c            K   sN   |r|d k	rd | _ n|| _ tj| f|||||d|
 || _|	| _|| _d S )N)r   r-   rP   r   rQ   )r"  r   rg   rD   rI   r,  )re   rD   r"  r   r-   rP   r   rQ   r,  rI   rc   r<   r<   r=   rg     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.
        )rZ   rI   )re   r<   r<   r=   rE     s    
z%ModelChoiceField.get_limit_choices_toc                s*   t t| j|}| jd k	r&| jj |_|S )N)rr   r   __deepcopy__rD   all)re   memoresult)r   r<   r=   r-    s    
zModelChoiceField.__deepcopy__c             C   s   | j S )N)r   )re   r<   r<   r=   _get_queryset  s    zModelChoiceField._get_querysetc             C   s$   |d krd n|j  | _| j| j_d S )N)r.  r   choicesr-   )re   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.
        )rt   )re   r   r<   r<   r=   r+    s    z$ModelChoiceField.label_from_instancec             C   s   t | dr| jS | j| S )N_choices)rF   r4  r#  )re   r<   r<   r=   _get_choices  s    
	zModelChoiceField._get_choicesc                s.   t |dr"| jr|j| jS |jS t j|S )Nr$   )rF   r,  Zserializable_valuer   rr   r*  )re   rm   )r   r<   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   )r3   r,  r(   rD   r\   rB   r2   r   r[   DoesNotExistr   rR   )re   rm   keyr<   r<   r=   r     s    


zModelChoiceField.to_pythonc             C   s   t j| |S )N)r   validate)re   rm   r<   r<   r=   r8    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  )disabledrt   r*  )re   r   r/   initial_value
data_valuer<   r<   r=   r     s
    zModelChoiceField.has_changed)rY   rh   ri   r   r   r   r!  r#  rg   rE   r-  r1  r3  propertyrD   r+  r5  r   _set_choicesr2  r*  r   r8  r   r   r<   r<   )r   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"  )rr   rg   )re   rD   rc   )r   r<   r=   rg      s    z!ModelMultipleChoiceField.__init__c             C   s   |sg S t | j|S )N)r   _check_values)re   rm   r<   r<   r=   r     s    z"ModelMultipleChoiceField.to_pythonc             C   sz   | j |}| jr*| r*t| jd ddn| j rB| rB| jj S t|ttfsbt| jd dd| j	|}| j
| |S )Nr   )r   r   )r*  r   r   rR   rD   r  r(   r   r   r?  run_validators)re   rm   r   r<   r<   r=   r     s    



zModelMultipleChoiceField.cleanc                s   | j pd yt|}W n& tk
r<   t| jd ddY nX xT|D ]L}y| jjf  |i W qD ttfk
r   t| jd dd|idY qDX qDW | jjf d  |i} fdd|D }x0|D ](}t||krt| jd	 d	d
|idqW |S )z
        Given a list of possible PK values, 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 r<   )rt   rB   )rL   r   )r7  r<   r=   rp   1  s    z9ModelMultipleChoiceField._check_values.<locals>.<setcomp>r  rm   )	r,  	frozensetr[   r   rR   rD   r  r   rt   )re   rm   r   r   Zpksvalr<   )r7  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 r<   r<   )rL   ro   )r*  r<   r=   rN   @  s    z:ModelMultipleChoiceField.prepare_value.<locals>.<listcomp>)rF   r(   rt   rr   r*  )re   rm   )r   )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 r<   )rt   )rL   rm   r<   r<   r=   rp   L  s    z7ModelMultipleChoiceField.has_changed.<locals>.<setcomp>c             S   s   h | ]}t |qS r<   )rt   )rL   rm   r<   r<   r=   rp   M  s    )r9  r   r*  )re   r   r/   initial_setdata_setr<   r<   r=   r   C  s    z$ModelMultipleChoiceField.has_changed)rY   rh   ri   r   r   r-   r   hidden_widgetr   r   rg   r   r   r?  r*  r   r   r<   r<   )r   r=   r     s   %c             C   s"   t | do | jjd k	p | jjd k	S )Nr$   )rF   r$   r&   r9   )rS   r<   r<   r=   modelform_defines_fieldsQ  s    
rG  )r   r   r   r   r   r   r   r   r   r   r   r    )NN)NN)	NNNNNNNNN)NF)3r   	itertoolsr   django.core.exceptionsr   r   r   r   django.forms.fieldsr   r   django.forms.formsr	   r
   django.forms.formsetsr   r   django.forms.utilsr   django.forms.widgetsr   r   r   django.utils.textr   r   django.utils.translationr   r   r   r!   r   r>   r   rJ   r   rd   rj   r   r   r    r   r   r   r  r   r   r!  r   r   rG  r<   r<   r<   r=   <module>   sj      
)
   VH @R  .d
7&)q\