U
    ƽbV                    @   s8  d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlm	Z	 d dl
mZ d dlmZ d dlmZ d dlmZ d dlmZmZmZmZmZmZmZmZmZ d dlmZ d d	lmZ  d d
l!m"Z" d dl#m$Z$m%Z%m&Z&m'Z' d dl(m)Z) d dl*m+Z+m,Z, d dl-m.Z.m/Z/ d dl0m1Z1 d dl2m3Z3 d dl4m5Z6 d dl7m8Z8 d dl9m:Z:m;Z;m<Z< d dl=m>Z>mZ d dl?m@Z@ d dlAmBZBmCZCmDZDmEZE d dlFmGZG d dlHmIZI G dd dZJG dd deKZLdd ZMdd  ZNd!d" ZOd#d$ ZPd%d& ZQdud'd(ZRd)d* ZSG d+d, d,ZTG d-d. d.ZUG d/d0 d0eKZVeWeXd1ZYd2ZZd3Z[d4Z\d5Z]d6Z^G d7d8 d8Z_G d9d: d:e_Z`G d;d< d<e`ZaG d=d> d>e_ZbG d?d@ d@ebZcG dAdB dBebZdG dCdD dDebZeG dEdF dFebZfG dGdH dHe_ZgG dIdJ dJebZhG dKdL dLe_ZiG dMdN dNe_ZjG dOdP dPe_ZkG dQdR dRe_ZlG dSdT dTe_ZmG dUdV dVe_ZnG dWdX dXe_ZoG dYdZ dZe_ZpG d[d\ d\epZqG d]d^ d^epZG d_d` d`e_ZrG dadb dberZG dcdd dde_ZsG dedf dfe_ZtG dgdh dhe_ZuG didj djeuZvG dkdl dle_ZwG dmdn dne_ZxG dodp dpe_ZyG dqdr dre_ZzG dsdt dte_Z{dS )v    N)OrderedDict)Mapping)settings)ObjectDoesNotExist)ValidationError)	EmailValidatorMaxLengthValidatorMaxValueValidatorMinLengthValidatorMinValueValidatorProhibitNullCharactersValidatorRegexValidatorURLValidatorip_address_validators)FilePathField)
ImageFieldtimezone)
parse_dateparse_datetimeparse_duration
parse_timeduration_string)is_protected_type	smart_str)localize_inputsanitize_separators)clean_ipv6_address)utc)gettext_lazy)InvalidTimeError)ISO_8601RemovedInDRF313WarningRemovedInDRF314Warning)ErrorDetailr   )api_settings)htmlhumanize_datetimejsonrepresentation)lazy_format)$ProhibitSurrogateCharactersValidatorc                   @   s   e Zd ZdZdS )emptyz
    This class is used to represent no data being provided for a given input
    or output value.

    It is required because `None` may be a valid input or output value.
    N__name__
__module____qualname____doc__ r3   r3   9/tmp/pip-unpacked-wheel-iohwuy7z/rest_framework/fields.pyr-   ,   s   r-   c                   @   s   e Zd ZdZdS )BuiltinSignatureErrorz
    Built-in function signatures are not inspectable. This exception is raised
    so the serializer can raise a helpful error message.
    Nr.   r3   r3   r3   r4   r5   6   s   r5   c                 C   s\   t | rtdt | s6t | s6t| tjs6dS t | }|j	
 }tdd |D S )zC
    True if the object is a callable that takes no arguments.
    zkBuilt-in function signatures are not inspectable. Wrap the function call in a simple, pure Python function.Fc                 s   s2   | ]*}|j |jkp(|j |jkp(|j|jkV  qd S N)kindVAR_POSITIONALVAR_KEYWORDdefaultr-   ).0paramr3   r3   r4   	<genexpr>M   s
   
z%is_simple_callable.<locals>.<genexpr>)inspect	isbuiltinr5   
isfunctionismethod
isinstance	functoolspartial	signature
parametersvaluesall)objsigparamsr3   r3   r4   is_simple_callable>   s    
 

rL   c                 C   s   |D ]}z"t | tr| | } n
t| |} W n tk
rB   Y  dS X t| rz
|  } W q ttfk
r } ztd||W 5 d}~X Y qX q| S )z
    Similar to Python's built in `getattr(instance, attr)`,
    but takes a list of nested attributes, instead of a single attribute.

    Also accepts either attribute lookup on objects or dictionary lookups.
    NzGException raised in callable attribute "{}"; original exception was: {})	rB   r   getattrr   rL   AttributeErrorKeyError
ValueErrorformat)instanceattrsattrexcr3   r3   r4   get_attributeU   s    



$rV   c                 C   sL   |s|  | dS |dd D ]}|| kr2i | |< | | } q|| |d < dS )a1  
    Similar to Python's built in `dictionary[key] = value`,
    but takes a list of nested keys instead of a single key.

    set_value({'a': 1}, [], {'b': 2}) -> {'a': 1, 'b': 2}
    set_value({'a': 1}, ['x'], 2) -> {'a': 1, 'x': 2}
    set_value({'a': 1}, ['x', 'y'], 2) -> {'a': 1, 'x': {'y': 2}}
    N)update)
dictionarykeysvaluekeyr3   r3   r4   	set_valuep   s    	

r]   c                 C   sX   t  }| D ]H}t|ttfs&|||< q
|\}}t|ttfrJt|||< q
|||< q
|S )z
    Convert choices into key/value dicts.

    to_choices_dict([1]) -> {1: 1}
    to_choices_dict([(1, '1st'), (2, '2nd')]) -> {1: '1st', 2: '2nd'}
    to_choices_dict([('Group', ((1, '1st'), 2))]) -> {'Group': {1: '1st', 2: '2'}}
    )r   rB   listtupleto_choices_dict)choicesretchoicer\   r[   r3   r3   r4   r`      s    

r`   c                 C   sJ   t  }|  D ]6\}}t|tr<| D ]\}}|||< q(q|||< q|S )z
    Convert a group choices dict into a flat dict of choices.

    flatten_choices_dict({1: '1st', 2: '2nd'}) -> {1: '1st', 2: '2nd'}
    flatten_choices_dict({'Group': {1: '1st', 2: '2nd'}}) -> {1: '1st', 2: '2nd'}
    )r   itemsrB   dict)ra   rb   r\   r[   sub_key	sub_valuer3   r3   r4   flatten_choices_dict   s    

rh   c                 c   s   G dd d}G dd d}G dd d}d}|   D ]\}}|rN||krN qt|tr||dV  |  D ].\}	}
|r||kr q||	|
d	V  |d
7 }ql| V  q6|||d	V  |d
7 }q6|r||kr|r|j|d}|d|ddV  dS )zE
    Helper function for options and option groups in templates.
    c                   @   s   e Zd ZdZdZdd ZdS )z&iter_options.<locals>.StartOptionGroupTFc                 S   s
   || _ d S r6   label)selfrj   r3   r3   r4   __init__   s    z/iter_options.<locals>.StartOptionGroup.__init__Nr/   r0   r1   start_option_groupend_option_grouprl   r3   r3   r3   r4   StartOptionGroup   s   rp   c                   @   s   e Zd ZdZdZdS )z$iter_options.<locals>.EndOptionGroupFTN)r/   r0   r1   rn   ro   r3   r3   r3   r4   EndOptionGroup   s   rq   c                   @   s   e Zd ZdZdZdddZdS )ziter_options.<locals>.OptionFc                 S   s   || _ || _|| _d S r6   r[   display_textdisabled)rk   r[   rs   rt   r3   r3   r4   rl      s    z%iter_options.<locals>.Option.__init__N)Frm   r3   r3   r3   r4   Option   s   ru   r   ri   )r[   rs      )countzn/aTrr   N)rd   rB   re   rQ   )grouped_choicescutoffcutoff_textrp   rq   ru   rw   r\   r[   rf   rg   r3   r3   r4   iter_options   s(    	



r{   c                    sZ   t | ddpd z
| j}W n( tk
rB    fdd| jD  Y S X  fdd| D S )zf
    Given a Django ValidationError, return a list of ErrorDetail,
    with the `code` populated.
    codeNinvalidc                    s8   g | ]0}t |jr|j|j n|j|jr,|jn d qS r|   r%   rK   messager|   r;   errorr   r3   r4   
<listcomp>   s   z$get_error_detail.<locals>.<listcomp>c                    s$   i | ]\}}| fd d|D qS )c                    s8   g | ]0}t |jr|j|j n|j|jr,|jn d qS r~   r   r   r   r3   r4   r      s   z/get_error_detail.<locals>.<dictcomp>.<listcomp>r3   )r;   kerrorsr   r3   r4   
<dictcomp>   s
    
z$get_error_detail.<locals>.<dictcomp>)rM   
error_dictrN   Z
error_listrd   )exc_infor   r3   r   r4   get_error_detail   s    


r   c                   @   s,   e Zd ZdZdZdd Zdd Zdd Zd	S )
CreateOnlyDefaultz
    This class may be used to provide default values that are only used
    for create operations, but that do not return any value for update
    operations.
    Tc                 C   s
   || _ d S r6   r:   )rk   r:   r3   r3   r4   rl     s    zCreateOnlyDefault.__init__c                 C   sn   |j jd k	}|rt t| jrht| jdrHtjdtdd | j	|  t
| jddr`| |S |  S | jS )Nset_contextMethod `set_context` on defaults is deprecated and will no longer be called starting with 3.13. Instead set `requires_context = True` on the class, and accept the context as an additional argument.   
stacklevelrequires_contextF)parentrR   	SkipFieldcallabler:   hasattrwarningswarnr#   r   rM   )rk   serializer_fieldZ	is_updater3   r3   r4   __call__  s    
 
zCreateOnlyDefault.__call__c                 C   s   d| j jt| jf S )Nz%s(%s))	__class__r/   reprr:   rk   r3   r3   r4   __repr__  s    zCreateOnlyDefault.__repr__N)r/   r0   r1   r2   r   rl   r   r   r3   r3   r3   r4   r      s
   r   c                   @   s    e Zd ZdZdd Zdd ZdS )CurrentUserDefaultTc                 C   s   |j d jS )Nrequest)contextuser)rk   r   r3   r3   r4   r   !  s    zCurrentUserDefault.__call__c                 C   s   d| j j S )Nz%s())r   r/   r   r3   r3   r4   r   $  s    zCurrentUserDefault.__repr__N)r/   r0   r1   r   r   r   r3   r3   r3   r4   r     s   r   c                   @   s   e Zd ZdS )r   N)r/   r0   r1   r3   r3   r3   r4   r   (  s   r    z-May not set both `read_only` and `write_only`z+May not set both `read_only` and `required`z)May not set both `required` and `default`z-Field(read_only=True) should be ReadOnlyFieldzrValidationError raised by `{class_name}`, but error key `{key}` does not exist in the `error_messages` dictionary.c                       s  e Zd ZdZededdZg ZeZdZ	dddeedddddddddd	Z
d
d Zedd Zejdd Zdd Zdd Zdd Zdd Zdd Zdd ZefddZdd Zdd  Zd!d" Zd#d$ Zed%d& Zed'd( Z fd)d*Zd+d, Zd-d. Z  ZS )/Fieldr   zThis field is required.zThis field may not be null.)requirednullNF)	read_only
write_onlyr   r:   initialsourcerj   	help_textstyleerror_messages
validators
allow_nullc                C   sF  t j| _t  jd7  _|d kr,|tko*| }|r<|r<tt|rL|rLtt|r`|tk	r`tt|rv| jt krvtt|| _	|| _
|| _|| _|| _|tkr| jn|| _|| _|| _|	d kri n|	| _|| _| jtk	r|tk	r|| _|d k	rt|| _d | _d | _i }t| jjD ]}|t|di  q||
p8i  || _d S )Nrv   default_error_messages)r   _creation_counterr-   AssertionErrorNOT_READ_ONLY_WRITE_ONLYNOT_READ_ONLY_REQUIREDNOT_REQUIRED_DEFAULTr   USE_READONLYFIELDr   r   r   r:   r   r   rj   r   r   r   default_empty_htmlr^   r   
field_namer   reversed__mro__rX   rM   r   )rk   r   r   r   r:   r   r   rj   r   r   r   r   r   messagesclsr3   r3   r4   rl   C  s<    

zField.__init__c                 C   s   | j |ks$td|| jj|jjf || _|| _| jdkrL|dd | _| j dkr\|| _ | j dkrng | _	n| j 
d| _	dS )z
        Initializes the field name and parent for the field instance.
        Called when a field is added to the parent serializer instance.
        zIt is redundant to specify `source='%s'` on field '%s' in serializer '%s', because it is the same as the field name. Remove the `source` keyword argument.N_ *.)r   r   r   r/   r   r   rj   replace
capitalizesource_attrssplitrk   r   r   r3   r3   r4   bindq  s    	


z
Field.bindc                 C   s   t | ds|  | _| jS )N_validators)r   get_validatorsr   r   r3   r3   r4   r     s    

zField.validatorsc                 C   s
   || _ d S r6   )r   )rk   r   r3   r3   r4   r     s    c                 C   s
   t | jS r6   )r^   default_validatorsr   r3   r3   r4   r     s    zField.get_validatorsc                 C   s   t | jr|  S | jS )z
        Return a value to use when the field is being returned as a primitive
        value, without any object instance.
        )r   r   r   r3   r3   r4   get_initial  s    
zField.get_initialc                 C   s   t |r~| j|kr,t| jddr&tS | jS || j }|dkrX| jrXt| ddrTdS dS |dkrz| jszt| ddrvdS tS |S |	| jtS )z
        Given the *incoming* primitive data, return the value for this field
        that should be validated and transformed to a native value.
        rD   Fr   allow_blankN)
r'   is_html_inputr   rM   rootr-   r   r   r   get)rk   rY   rb   r3   r3   r4   	get_value  s    


zField.get_valuec              
   C   s   zt || jW S  tk
rX } z,dj| jjj| j|jjd}t||W 5 d}~X Y n t	t
fk
r } zl| jtk	r|   W Y TS | jrW Y FdS | jst djt|j| j| jjj|jj|d}t||W 5 d}~X Y nX dS )z~
        Given the *outgoing* object instance, return the primitive value
        that should be used for this field.
        zField source for `{serializer}.{field}` maps to a built-in function type and is invalid. Define a property or method on the `{instance}` instance that wraps the call to the built-in function.)
serializerfieldrR   NzGot {exc_type} when attempting to get a value for field `{field}` on serializer `{serializer}`.
The serializer field might be named incorrectly and not match any attribute or key on the `{instance}` instance.
Original exception text was: {exc}.)exc_typer   r   rR   rU   )rV   r   r5   rQ   r   r   r/   r   typerO   rN   r:   r-   get_defaultr   r   r   )rk   rR   rU   msgr3   r3   r4   rV     s4    


zField.get_attributec                 C   sv   | j tkst| jddrt t| j rpt| j drPtjdt	dd | j 
|  t| j ddrh|  | S |   S | j S )a2  
        Return the default value to use when validating data if no input
        is provided for this field.

        If a default has not been set for this field then this will simply
        raise `SkipField`, indicating that no value should be set in the
        validated data for this field.
        rD   Fr   r   r   r   r   )r:   r-   rM   r   r   r   r   r   r   r#   r   r   r3   r3   r4   r     s    	
 
zField.get_defaultc                 C   s~   | j rd|  fS |tkrJt| jddr.t | jr>| d d|  fS |dkrv| jsd| d n| j	dkrrdS d	S d|fS )
a  
        Validate empty values, and either:

        * Raise `ValidationError`, indicating invalid data.
        * Raise `SkipField`, indicating that the field should be ignored.
        * Return (True, data), indicating an empty value that should be
          returned without any further validation being applied.
        * Return (False, data), indicating a non-empty value, that should
          have validation applied as normal.
        TrD   Fr   Nr   r   )FNTN)
r   r   r-   rM   r   r   r   failr   r   rk   datar3   r3   r4   validate_empty_values
  s    

zField.validate_empty_valuesc                 C   s.   |  |\}}|r|S | |}| | |S )a  
        Validate a simple representation and return the internal value.

        The provided data may be `empty` if no representation was included
        in the input.

        May raise `SkipField` if the field should not be included in the
        validated data.
        )r   to_internal_valuerun_validators)rk   r   Zis_empty_valuer[   r3   r3   r4   run_validation+  s    


zField.run_validationc                 C   s   g }| j D ]}t|dr2tjdtdd ||  z$t|ddrL|||  n|| W q
 tk
r } zt|j	t
rv ||j	 W 5 d}~X Y q
 tk
r } z|t| W 5 d}~X Y q
X q
|rt|dS )z
        Test the given value against all the validators on the field,
        and either raise a `ValidationError` or simply return.
        r   zMethod `set_context` on validators is deprecated and will no longer be called starting with 3.13. Instead set `requires_context = True` on the class, and accept the context as an additional argument.r   r   r   FN)r   r   r   r   r#   r   rM   r   rB   detailre   extendDjangoValidationErrorr   )rk   r[   r   	validatorrU   r3   r3   r4   r   <  s*    

 
"zField.run_validatorsc                 C   s   t dj| jj| jddS )zN
        Transform the *incoming* primitive data into a native value.
        z{cls}.to_internal_value() must be implemented for field {field_name}. If you do not need to support write operations you probably want to subclass `ReadOnlyField` instead.r   r   NNotImplementedErrorrQ   r   r/   r   r   r3   r3   r4   r   ^  s    zField.to_internal_valuec                 C   s   t dj| jj| jddS )zL
        Transform the *outgoing* native value into primitive data.
        zE{cls}.to_representation() must be implemented for field {field_name}.r   Nr   rk   r[   r3   r3   r4   to_representationk  s    zField.to_representationc                 K   s^   z| j | }W n2 tk
r@   | jj}tj||d}t|Y nX |jf |}t||ddS )zH
        A helper method that simply raises a validation error.
        )
class_namer\   r   N)r   rO   r   r/   MISSING_ERROR_MESSAGErQ   r   r   )rk   r\   kwargsr   r   Zmessage_stringr3   r3   r4   r   v  s    z
Field.failc                 C   s   | }|j dk	r|j }q|S )zB
        Returns the top-level serializer for this field.
        N)r   )rk   r   r3   r3   r4   r     s    
z
Field.rootc                 C   s   t | jdi S )zY
        Returns the context as passed to the root serializer on initialization.
        _context)rM   r   r   r3   r3   r4   r     s    zField.contextc                    s   t  | }||_||_|S )z
        When a field is instantiated, we store the arguments that were used,
        so that we can present a helpful representation of the object.
        )super__new___args_kwargs)r   argsr   rR   r   r3   r4   r     s    zField.__new__c                    s4   dd | j D } fdd| j D }| j||S )z
        When cloning fields we instantiate using the arguments it was
        originally created with, rather than copying the complete state.
        c                 S   s$   g | ]}t |tst|n|qS r3   )rB   
REGEX_TYPEcopydeepcopyr;   itemr3   r3   r4   r     s   z&Field.__deepcopy__.<locals>.<listcomp>c                    s*   i | ]"\}}||d kr"t | n|qS ))r   regex)r   r   )r;   r\   r[   memor3   r4   r     s    z&Field.__deepcopy__.<locals>.<dictcomp>)r   r   rd   r   )rk   r   r   r   r3   r   r4   __deepcopy__  s    
zField.__deepcopy__c                 C   s
   t | S )z
        Fields are represented using their initial calling arguments.
        This allows us to create descriptive representations for serializer
        instances that show all the declared fields on the serializer.
        )r*   Z
field_reprr   r3   r3   r4   r     s    zField.__repr__) r/   r0   r1   r   r   r   r   r-   r   r   rl   r   propertyr   setterr   r   r   rV   r   r   r   r   r   r   r   r   r   r   r   r   __classcell__r3   r3   r   r4   r   8  sT          .$

	)!"
	

r   c                   @   s   e Zd ZdediZdZdZdddddd	d
dddddddddhZddddddddddddd d!d"d#dhZd$d%d&d'd(hZ	d)d* Z
d+d, Zd(S )-BooleanFieldr}   zMust be a valid boolean.FtTyYyesZYesZYEStrueTrueTRUEonZOnON1rv   TfFnNnoZNoNOfalseFalseFALSEoffZOffZOFF0r   g        r   ZNullZNULLr   Nc                 C   sb   z:|| j krW dS || jkr"W dS || jkr8| jr8W d S W n tk
rN   Y nX | jd|d d S )NTFr}   input)TRUE_VALUESFALSE_VALUESNULL_VALUESr   	TypeErrorr   r   r3   r3   r4   r     s    


zBooleanField.to_internal_valuec                 C   s8   || j krdS || jkrdS || jkr0| jr0d S t|S )NTF)r  r  r  r   boolr   r3   r3   r4   r     s    

zBooleanField.to_representation)r/   r0   r1   r   r   r   r   r  r  r  r   r   r3   r3   r3   r4   r     sV              	           r   c                       s    e Zd ZdZ fddZ  ZS )NullBooleanFieldNc                    s:   t jdtdd d|ks tdd|d< t jf | d S )NzThe `NullBooleanField` is deprecated and will be removed starting with 3.14. Instead use the `BooleanField` field and set `allow_null=True` which does the same thing.r   r   r   z#`allow_null` is not a valid option.T)r   r   r$   r   r   rl   rk   r   r   r3   r4   rl     s     zNullBooleanField.__init__)r/   r0   r1   r   rl   r   r3   r3   r   r4   r    s   r  c                       s^   e Zd ZededededdZdZ fddZef fd	d
	Zdd Z	dd Z
  ZS )	CharFieldzNot a valid string.zThis field may not be blank.;Ensure this field has no more than {max_length} characters.z7Ensure this field has at least {min_length} characters.)r}   blank
max_length
min_lengthr   c                    s   | dd| _| dd| _| dd | _| dd | _t jf | | jd k	rzt| jd | jd}| j	
t| j|d | jd k	rt| jd | jd	}| j	
t| j|d | j	
t  | j	
t  d S )
Nr   Ftrim_whitespaceTr   r!  r   r   r!  )popr   r"  r   r!  r   rl   r+   r   r   appendr   r
   r   r,   rk   r   r   r   r3   r4   rl     s"    

zCharField.__init__c                    s>   |dks| j r2t| dkr2| js.| d dS t |S )Nr   r  )r"  strstripr   r   r   r   r   r   r3   r4   r     s
    
zCharField.run_validationc                 C   s>   t |tst |tttfs$| d t|}| jr:| S |S )Nr}   )rB   r  r)  intfloatr   r"  r*  rk   r   r[   r3   r3   r4   r   !  s    
zCharField.to_internal_valuec                 C   s   t |S r6   r)  r   r3   r3   r4   r   *  s    zCharField.to_representation)r/   r0   r1   r   r   r   rl   r-   r   r   r   r   r3   r3   r   r4   r    s   
	r  c                       s(   e Zd ZdediZ fddZ  ZS )
EmailFieldr}   zEnter a valid email address.c                    s.   t  jf | t| jd d}| j| d S Nr}   r$  )r   rl   r   r   r   r'  rk   r   r   r   r3   r4   rl   3  s    zEmailField.__init__r/   r0   r1   r   r   rl   r   r3   r3   r   r4   r/  .  s    r/  c                       s(   e Zd ZdediZ fddZ  ZS )
RegexFieldr}   z/This value does not match the required pattern.c                    s0   t  jf | t|| jd d}| j| d S r0  )r   rl   r   r   r   r'  )rk   r   r   r   r   r3   r4   rl   >  s    zRegexField.__init__r2  r3   r3   r   r4   r3  9  s    r3  c                       s0   e Zd ZededdZd fdd	Z  ZS )	SlugFieldzLEnter a valid "slug" consisting of letters, numbers, underscores or hyphens.zUEnter a valid "slug" consisting of Unicode letters, numbers, underscores, or hyphens.)r}   invalid_unicodeFc                    s`   t  jf | || _| jr8ttdtj| jd d}nttd| jd d}| j	| d S )Nz	^[-\w]+\Zr5  r$  z^[-a-zA-Z0-9_]+$r}   )
r   rl   allow_unicoder   recompileUNICODEr   r   r'  )rk   r6  r   r   r   r3   r4   rl   J  s    zSlugField.__init__)Fr2  r3   r3   r   r4   r4  D  s   r4  c                       s(   e Zd ZdediZ fddZ  ZS )URLFieldr}   zEnter a valid URL.c                    s.   t  jf | t| jd d}| j| d S r0  )r   rl   r   r   r   r'  r1  r   r3   r4   rl   Y  s    zURLField.__init__r2  r3   r3   r   r4   r:  T  s    r:  c                       s<   e Zd ZdZdediZ fddZdd Zdd	 Z  Z	S )
	UUIDField)hex_verbosehexr+  Zurnr}   zMust be a valid UUID.c                    sB   | dd| _| j| jkr0tdd| jt jf | d S )NrQ   r<  z;Invalid format for uuid representation. Must be one of "{}"z", ")r&  uuid_formatvalid_formatsrP   rQ   joinr   rl   r  r   r3   r4   rl   f  s    
zUUIDField.__init__c                 C   sv   t |tjsrzBt |tr&tj|dW S t |tr>tj|dW S | jd|d W n" tk
rp   | jd|d Y nX |S )Nr+  )r=  r}   r[   )rB   uuidUUIDr+  r)  r   rP   r   r3   r3   r4   r   o  s    

zUUIDField.to_internal_valuec                 C   s"   | j dkrt|S t|| j S d S )Nr<  )r>  r)  rM   r   r3   r3   r4   r   |  s    
zUUIDField.to_representation)
r/   r0   r1   r?  r   r   rl   r   r   r   r3   r3   r   r4   r;  _  s    	r;  c                       s:   e Zd ZdZdediZd	 fdd	Z fddZ  ZS )
IPAddressFieldz5Support both IPAddressField and GenericIPAddressFieldr}   z#Enter a valid IPv4 or IPv6 address.bothc                    sD   |  | _| jdk| _t jf | t|| j\}}| j| d S )NrF  )lowerprotocolunpack_ipv4r   rl   r   r   r   )rk   rH  r   r   error_messager   r3   r4   rl     s
    
zIPAddressField.__init__c                    sl   t |ts| jd|d d|kr`z| jdkr:t|| jW S W n" tk
r^   | jd|d Y nX t |S )Nr}   rB  :)rF  Zipv6)	rB   r)  r   rH  r   rI  r   r   r   r   r   r3   r4   r     s    

z IPAddressField.to_internal_value)rF  )	r/   r0   r1   r2   r   r   rl   r   r   r3   r3   r   r4   rE    s    rE  c                       sX   e Zd ZededededdZdZedZ fdd	Z	d
d Z
dd Z  ZS )IntegerFieldzA valid integer is required.7Ensure this value is less than or equal to {max_value}.:Ensure this value is greater than or equal to {min_value}.String value too large.r}   	max_value	min_valuemax_string_length  z\.0*\s*$c                    s   | dd | _| dd | _t jf | | jd k	r^t| jd | jd}| jt	| j|d | jd k	rt| jd | jd}| jt
| j|d d S NrQ  rR  rQ  r$  rR  r&  rQ  rR  r   rl   r+   r   r   r'  r	   r   r(  r   r3   r4   rl     s    

zIntegerField.__init__c              	   C   sd   t |tr"t|| jkr"| d zt| jdt|}W n" tt	fk
r^   | d Y nX |S )NrS  r   r}   )
rB   r)  lenMAX_STRING_LENGTHr   r+  
re_decimalsubrP   r  r   r3   r3   r4   r     s    
zIntegerField.to_internal_valuec                 C   s   t |S r6   rA  r   r3   r3   r4   r     s    zIntegerField.to_representation)r/   r0   r1   r   r   rZ  r7  r8  r[  rl   r   r   r   r3   r3   r   r4   rL    s   

rL  c                       sN   e Zd ZededededdZdZ fddZd	d
 Zdd Z  Z	S )
FloatFieldA valid number is required.rM  rN  rO  rP  rT  c                    s   | dd | _| dd | _t jf | | jd k	r^t| jd | jd}| jt	| j|d | jd k	rt| jd | jd}| jt
| j|d d S rU  rX  r(  r   r3   r4   rl     s    

zFloatField.__init__c              	   C   sT   t |tr"t|| jkr"| d z
t|W S  ttfk
rN   | d Y nX d S )NrS  r}   )rB   r)  rY  rZ  r   r,  r  rP   r   r3   r3   r4   r     s    

zFloatField.to_internal_valuec                 C   s   t |S r6   )r,  r   r3   r3   r4   r     s    zFloatField.to_representation)
r/   r0   r1   r   r   rZ  rl   r   r   r   r3   r3   r   r4   r]    s   
r]  c                       s~   e Zd ZedededededededdZd	Zd fdd	Z fddZdd Zdd Z	dd Z
dd Z  ZS )DecimalFieldr^  rM  rN  z@Ensure that there are no more than {max_digits} digits in total.zGEnsure that there are no more than {max_decimal_places} decimal places.zVEnsure that there are no more than {max_whole_digits} digits before the decimal point.rO  )r}   rQ  rR  
max_digitsmax_decimal_placesmax_whole_digitsrS  rT  NFc                    s  || _ || _|| _|d k	r || _| jr,d| _|| _|| _| j d k	r\| jd k	r\| j | j | _nd | _t jf | | jd k	rt	| j
d | jd}	| jt| j|	d | jd k	rt	| j
d | jd}	| jt| j|	d |d k	rdd tt D }
||
kstd	||
f || _d S )
NTrQ  rV  r$  rR  rW  c                 S   s   g | ]\}}| d r|qS )ZROUND_)
startswith)r;   r   vr3   r3   r4   r     s     
 z)DecimalField.__init__.<locals>.<listcomp>z=Invalid rounding option %s. Valid values for rounding are: %s)r`  decimal_placeslocalizecoerce_to_stringrQ  rR  rb  r   rl   r+   r   r   r'  r	   r   varsdecimalrd   r   rounding)rk   r`  re  rg  rQ  rR  rf  rj  r   r   Zvalid_roundingsr   r3   r4   rl     s:    



zDecimalField.__init__c                    s&   t | dkr| jrdS t |S )Nr   r   )r   r*  r   r   r   r   r   r3   r4   r     s    z"DecimalField.validate_empty_valuesc                 C   s   t | }| jrt|}t|| jkr2| d zt|}W n  tj	k
r`   | d Y nX |
 rt| d |tdtdfkr| d | | |S )zd
        Validate that the input is a decimal number and return a Decimal
        instance.
        rS  r}   ZInfz-Inf)r   r*  rf  r   rY  rZ  r   ri  DecimalDecimalExceptionis_nanquantizevalidate_precisionr-  r3   r3   r4   r     s    


zDecimalField.to_internal_valuec                 C   s   |  \}}}|dkr,t|| }|}d}n>t|t|krZt|}|t| }t|}nt|}d}|}| jdk	r|| jkr| jd| jd | jdk	r|| jkr| jd| jd | jdk	r|| jkr| jd| jd |S )	a  
        Ensure that there are no more than max_digits in the number, and no
        more than decimal_places digits after the decimal point.

        Override this method to disable the precision validation for input
        values or to enhance it in any way you need to.
        r   Nr`  )r`  ra  )ra  rb  )rb  )as_tuplerY  absr`  r   re  rb  )rk   r[   signZ
digittupleexponentZtotal_digitsZwhole_digitsre  r3   r3   r4   ro  :  s&    
zDecimalField.validate_precisionc                 C   sj   t | dtj}|d kr"|rdS d S t|tjs@tt| }| |}|sR|S | j	r`t
|S d|S )Nrg  r   z{:f})rM   r&   ZCOERCE_DECIMAL_TO_STRINGrB   ri  rk  r)  r*  rn  rf  r   rQ   )rk   r[   rg  Z	quantizedr3   r3   r4   r   ]  s    
zDecimalField.to_representationc                 C   sJ   | j dkr|S t  }| jdk	r,| j|_|jtd| j  | j|dS )zI
        Quantize the decimal value to the configured precision.
        Nz.1)rj  r   )	re  ri  
getcontextr   r`  precrn  rk  rj  )rk   r[   r   r3   r3   r4   rn  r  s    

zDecimalField.quantize)NNNFN)r/   r0   r1   r   r   rZ  rl   r   r   ro  r   rn  r   r3   r3   r   r4   r_    s$   	    ##r_  c                       sj   e Zd ZededededdZejjZeddf fdd	Z	d	d
 Z
dd Zdd Zdd Z  ZS )DateTimeFieldzFDatetime has wrong format. Use one of these formats instead: {format}.z#Expected a datetime but got a date.z/Invalid datetime for the timezone "{timezone}".zDatetime value out of range.)r}   date
make_awareoverflowNc                    s<   |t k	r|| _|d k	r|| _|d k	r*|| _t jf | d S r6   )r-   rQ   input_formatsr   r   rl   )rk   rQ   rz  default_timezoner   r   r3   r4   rl     s    zDateTimeField.__init__c                 C   s   t | d|  }|dk	rt|rNz||W S  tk
rL   | d Y nX zt||W S  tk
r~   | jd|d Y qX n|dkrt|rt	|t
S |S )z
        When `self.default_timezone` is `None`, always return naive datetimes.
        When `self.default_timezone` is not `None`, always return aware datetimes.
        r   Nry  rx  r   )rM   r{  r   Zis_aware
astimezoneOverflowErrorr   rx  r!   Z
make_naiver   )rk   r[   Zfield_timezoner3   r3   r4   enforce_timezone  s    
zDateTimeField.enforce_timezonec                 C   s   t jrt S d S r6   )r   ZUSE_TZr   Zget_current_timezoner   r3   r3   r4   r{    s    zDateTimeField.default_timezonec              
   C   s   t | dtj}t|tjr0t|tjs0| d t|tjrF| |S |D ]}| t	krz$t
|}|d k	r|| |W   S W q ttfk
r   Y qX qJz| ||}| |W   S  ttfk
r   Y qJX qJt|}| jd|d d S )Nrz  rw  r}   rQ   )rM   r&   ZDATETIME_INPUT_FORMATSrB   datetimerw  r   r~  rG  r"   r   rP   r  datetime_parserr(   Zdatetime_formatsrk   r[   rz  Zinput_formatparsedZhumanized_formatr3   r3   r4   r     s(    


zDateTimeField.to_internal_valuec                 C   sr   |sd S t | dtj}|d ks(t|tr,|S | |}| tkrh| }|	drd|d d d }|S |
|S )NrQ   z+00:00iZ)rM   r&   ZDATETIME_FORMATrB   r)  r~  rG  r"   	isoformatendswithstrftimerk   r[   Zoutput_formatr3   r3   r4   r     s    

zDateTimeField.to_representation)r/   r0   r1   r   r   r  strptimer  r-   rl   r~  r{  r   r   r   r3   r3   r   r4   rv    s   	rv  c                       sL   e Zd ZededdZejjZedf fdd	Z	dd Z
d	d
 Z  ZS )	DateFieldzBDate has wrong format. Use one of these formats instead: {format}.z#Expected a date but got a datetime.)r}   r  Nc                    s.   |t k	r|| _|d k	r|| _t jf | d S r6   r-   rQ   rz  r   rl   rk   rQ   rz  r   r   r3   r4   rl     s
    zDateField.__init__c              
   C   s   t | dtj}t|tjr$| d t|tjr4|S |D ]~}| tkrzt	|}W n t
tfk
rl   Y qX |d k	r|  S q8z| ||}W n t
tfk
r   Y q8X |   S q8t|}| jd|d d S )Nrz  r  r}   r  )rM   r&   ZDATE_INPUT_FORMATSrB   r  r   rw  rG  r"   r   rP   r  r  r(   Zdate_formatsr  r3   r3   r4   r     s(    


zDateField.to_internal_valuec                 C   s^   |sd S t | dtj}|d ks(t|tr,|S t|tjr@td| tkrT|	 S |
|S )NrQ   zExpected a `date`, but got a `datetime`. Refusing to coerce, as this may mean losing timezone information. Use a custom read-only field and deal with timezone issues explicitly.)rM   r&   ZDATE_FORMATrB   r)  r  r   rG  r"   r  r  r  r3   r3   r4   r     s    zDateField.to_representationr/   r0   r1   r   r   r  r  r  r-   rl   r   r   r   r3   r3   r   r4   r    s   r  c                       sF   e Zd ZdediZejjZedf fdd	Z	dd Z
dd	 Z  ZS )
	TimeFieldr}   zBTime has wrong format. Use one of these formats instead: {format}.Nc                    s.   |t k	r|| _|d k	r|| _t jf | d S r6   r  r  r   r3   r4   rl   &  s
    zTimeField.__init__c              
   C   s   t | dtj}t|tjr|S |D ]~}| tkrjzt|}W n t	t
fk
rV   Y qX |d k	r|  S q"z| ||}W n t	t
fk
r   Y q"X |   S q"t|}| jd|d d S )Nrz  r}   r  )rM   r&   ZTIME_INPUT_FORMATSrB   r  timerG  r"   r   rP   r  r  r(   Ztime_formatsr   r  r3   r3   r4   r   -  s$    

zTimeField.to_internal_valuec                 C   sb   |dkrd S t | dtj}|d ks,t|tr0|S t|tjrDtd| tkrX|	 S |
|S )N)Nr   rQ   zExpected a `time`, but got a `datetime`. Refusing to coerce, as this may mean losing timezone information. Use a custom read-only field and deal with timezone issues explicitly.)rM   r&   ZTIME_FORMATrB   r)  r  r   rG  r"   r  r  r  r3   r3   r4   r   G  s    zTimeField.to_representationr  r3   r3   r   r4   r     s    r  c                       sD   e Zd ZedededdZ fddZdd Zd	d
 Z  ZS )DurationFieldzFDuration has wrong format. Use one of these formats instead: {format}.rM  rN  )r}   rQ  rR  c                    s   | dd | _| dd | _t jf | | jd k	r^t| jd | jd}| jt	| j|d | jd k	rt| jd | jd}| jt
| j|d d S rU  rX  r(  r   r3   r4   rl   e  s    

zDurationField.__init__c                 C   s:   t |tjr|S tt|}|d k	r(|S | jddd d S )Nr}   z[DD] [HH:[MM:]]ss[.uuuuuu]r  )rB   r  	timedeltar   r)  r   )rk   r[   r  r3   r3   r4   r   r  s    zDurationField.to_internal_valuec                 C   s   t |S r6   r   r   r3   r3   r4   r   z  s    zDurationField.to_representation	r/   r0   r1   r   r   rl   r   r   r   r3   r3   r   r4   r  ^  s   r  c                       sf   e Zd ZdediZdZedZ fddZdd Zd	d
 Z	dd Z
dd Zdd ZeeeZ  ZS )ChoiceFieldinvalid_choice "{input}" is not a valid choice.NzMore than {count} items...c                    sF   || _ |d| j| _|d| j| _|dd| _t jf | d S )Nhtml_cutoffhtml_cutoff_textr   F)ra   r&  r  r  r   r   rl   )rk   ra   r   r   r3   r4   rl     s
    zChoiceField.__init__c                 C   sJ   |dkr| j rdS z| jt| W S  tk
rD   | jd|d Y nX d S )Nr   r  r  )r   choice_strings_to_valuesr)  rO   r   r   r3   r3   r4   r     s    zChoiceField.to_internal_valuec                 C   s   |dkr|S | j t||S )N)r   Nr  r   r)  r   r3   r3   r4   r     s    zChoiceField.to_representationc                 C   s   t | j| j| jdS )zP
        Helper method for use with templates rendering select widgets.
        )ry   rz   )r{   rx   r  r  r   r3   r3   r4   r{     s
    zChoiceField.iter_optionsc                 C   s   | j S r6   )_choicesr   r3   r3   r4   _get_choices  s    zChoiceField._get_choicesc                 C   s,   t || _t| j| _dd | jD | _d S )Nc                 S   s   i | ]}t ||qS r3   r.  )r;   r\   r3   r3   r4   r     s     z,ChoiceField._set_choices.<locals>.<dictcomp>)r`   rx   rh   r  ra   r  )rk   ra   r3   r3   r4   _set_choices  s
    
zChoiceField._set_choices)r/   r0   r1   r   r   r  r  rl   r   r   r{   r  r  r   ra   r   r3   r3   r   r4   r    s    		
r  c                       sT   e Zd ZedededdZg Z fddZdd Z fd	d
Zdd Z	  Z
S )MultipleChoiceFieldr  5Expected a list of items but got type "{input_type}".z This selection may not be empty.)r  
not_a_listr-   c                    s    | dd| _t jf | d S )Nallow_emptyT)r&  r  r   rl   r  r   r3   r4   rl     s    zMultipleChoiceField.__init__c                 C   s@   | j |krt| jddrtS t|r2|| j S || j tS )NrD   F)r   rM   r   r-   r'   r   getlistr   rk   rY   r3   r3   r4   r     s    

zMultipleChoiceField.get_valuec                    sX   t |tst|ds( jdt|jd  jsDt|dkrD d  fdd|D S )N__iter__r  Z
input_typer   r-   c                    s   h | ]}t t|qS r3   )r   r  r   r   )r   rk   r3   r4   	<setcomp>  s   z8MultipleChoiceField.to_internal_value.<locals>.<setcomp>)rB   r)  r   r   r   r/   r  rY  r   r   r   r4   r     s    
z%MultipleChoiceField.to_internal_valuec                    s    fdd|D S )Nc                    s   h | ]} j t||qS r3   r  r   r   r3   r4   r    s    z8MultipleChoiceField.to_representation.<locals>.<setcomp>r3   r   r3   r   r4   r     s    
z%MultipleChoiceField.to_representation)r/   r0   r1   r   r   r   rl   r   r   r   r   r3   r3   r   r4   r    s   
r  c                       s*   e Zd ZdediZd fdd	Z  ZS )	r   r  z%"{input}" is not a valid path choice.NFTc           	         s0   t ||||||d}|j|d< t jf | d S )N)match	recursiveallow_filesallow_foldersr   ra   )DjangoFilePathFieldra   r   rl   )	rk   pathr  r  r  r  r   r   r   r   r3   r4   rl     s        
zFilePathField.__init__)NFTFNr2  r3   r3   r   r4   r     s        r   c                       sP   e Zd ZedededededdZ fddZd	d
 Zdd Z  ZS )	FileFieldzNo file was submitted.zGThe submitted data was not a file. Check the encoding type on the form.z No filename could be determined.zThe submitted file is empty.zKEnsure this filename has at most {max_length} characters (it has {length}).)r   r}   no_namer-   r   c                    sB   | dd | _| dd| _d|kr0| d| _t jf | d S )Nr   allow_empty_fileFuse_url)r&  r   r  r  r   rl   r  r   r3   r4   rl     s
    zFileField.__init__c                 C   s   z|j }|j}W n tk
r.   | d Y nX |s>| d | jsR|sR| d | jr|t|| jkr|| jd| jt|d |S )Nr}   r  r-   r   )r   length)namesizerN   r   r  r   rY  )rk   r   	file_name	file_sizer3   r3   r4   r     s    



zFileField.to_internal_valuec                 C   sf   |sd S t | dtj}|r`z
|j}W n tk
r:   Y d S X | jdd }|d k	r\||S |S |jS )Nr  r   )	rM   r&   ZUPLOADED_FILES_USE_URLurlrN   r   r   Zbuild_absolute_urir  )rk   r[   r  r  r   r3   r3   r4   r     s    

zFileField.to_representationr  r3   r3   r   r4   r    s   r  c                       s4   e Zd ZdediZ fddZ fddZ  ZS )r   Zinvalid_imagezYUpload a valid image. The file you uploaded was either not an image or a corrupted image.c                    s    | dt| _t jf | d S )N_DjangoImageField)r&  DjangoImageFieldr  r   rl   r  r   r3   r4   rl   /  s    zImageField.__init__c                    s&   t  |}|  }| j|_||S r6   )r   r   r  r   clean)rk   r   Zfile_objectZdjango_fieldr   r3   r4   r   3  s    zImageField.to_internal_value)r/   r0   r1   r   r   rl   r   r   r3   r3   r   r4   r   (  s    r   c                       s,   e Zd Z fddZdd Zdd Z  ZS )_UnvalidatedFieldc                    s   t  jf | d| _d| _d S NT)r   rl   r   r   r  r   r3   r4   rl   @  s    z_UnvalidatedField.__init__c                 C   s   |S r6   r3   r   r3   r3   r4   r   E  s    z#_UnvalidatedField.to_internal_valuec                 C   s   |S r6   r3   r   r3   r3   r4   r   H  s    z#_UnvalidatedField.to_representation)r/   r0   r1   rl   r   r   r   r3   r3   r   r4   r  ?  s   r  c                       sd   e Zd Ze Zg ZededededdZ fddZdd	 Z	d
d Z
dd Zdd Z  ZS )	ListFieldr  zThis list may not be empty.z5Ensure this field has at least {min_length} elements.z9Ensure this field has no more than {max_length} elements.)r  r-   r!  r   c                    s   | dt| j| _| dd| _| dd | _| dd | _t| jrTt	d| jj
d ksht	dt jf | | jjd| d	 | jd k	rt| jd | jd
}| jt| j|d | jd k	rt| jd | jd}| jt| j|d d S )Nchildr  Tr   r!  "`child` has not been instantiated.vThe `source` argument is not meaningful when applied to a `child=` field. Remove `source=` from the field declaration.r   r   r   r#  r$  r%  )r&  r   r   r  r  r   r!  r>   isclassr   r   r   rl   r   r+   r   r   r'  r   r
   r(  r   r3   r4   rl   V  s     

zListField.__init__c                 C   sd   | j |krt| jddrtS t|rV|| j g }t|dkrD|S tj|| j tdS |	| j tS )NrD   Fr   )prefixr:   )
r   rM   r   r-   r'   r   r  rY  parse_html_listr   )rk   rY   valr3   r3   r4   r   k  s    

zListField.get_valuec                 C   sj   t |rt j|g d}t|ttfs0t|dsD| jdt|j	d | j
s`t|dkr`| d | |S )zY
        List of dicts of native values <- List of dicts of primitive datatypes.
        r   r  r  r  r   r-   )r'   r   r  rB   r)  r   r   r   r   r/   r  rY  run_child_validationr   r3   r3   r4   r   z  s    

zListField.to_internal_valuec                    s    fdd|D S )zS
        List of object instances -> List of dicts of primitive datatypes.
        c                    s$   g | ]}|d k	r j |nd qS r6   )r  r   r   r   r3   r4   r     s     z/ListField.to_representation.<locals>.<listcomp>r3   r   r3   r   r4   r     s    zListField.to_representationc                 C   st   g }t  }t|D ]L\}}z|| j| W q tk
r\ } z|j||< W 5 d }~X Y qX q|sh|S t|d S r6   )r   	enumerater'  r  r   r   r   )rk   r   resultr   idxr   er3   r3   r4   r    s    zListField.run_child_validationr/   r0   r1   r  r  r   r   r   rl   r   r   r   r  r   r3   r3   r   r4   r  L  s   r  c                       sX   e Zd Ze Zi ZededdZ fddZdd Z	dd	 Z
d
d Zdd Z  ZS )	DictFieldz;Expected a dictionary of items but got type "{input_type}".z!This dictionary may not be empty.)
not_a_dictr-   c                    sn   | dt| j| _| dd| _t| jr8td| jjd ksLtdt	 j
f | | jjd| d d S )Nr  r  Tr  r  r   r  )r&  r   r   r  r  r>   r  r   r   r   rl   r   r  r   r3   r4   rl     s    zDictField.__init__c                 C   s(   t |rt j|| jdS || jtS )N)r  )r'   r   parse_html_dictr   r   r-   r  r3   r3   r4   r     s    
zDictField.get_valuec                 C   sX   t |rt |}t|ts2| jdt|jd | jsNt	|dkrN| d | 
|S )zI
        Dicts of native values <- Dicts of primitive datatypes.
        r  r  r   r-   )r'   r   r  rB   re   r   r   r/   r  rY  r  r   r3   r3   r4   r     s    



zDictField.to_internal_valuec                    s    fdd|  D S )Nc                    s.   i | ]&\}}t ||d k	r& j|nd qS r6   )r)  r  r   )r;   r\   r  r   r3   r4   r     s    z/DictField.to_representation.<locals>.<dictcomp>)rd   r   r3   r   r4   r     s    
zDictField.to_representationc                 C   sz   i }t  }| D ]R\}}t|}z| j|||< W q tk
rb } z|j||< W 5 d }~X Y qX q|sn|S t|d S r6   )r   rd   r)  r  r   r   r   )rk   r   r  r   r\   r[   r  r3   r3   r4   r    s    zDictField.run_child_validationr  r3   r3   r   r4   r    s   r  c                       s(   e Zd ZedddZ fddZ  ZS )HStoreFieldT)r   r   c                    s&   t  jf | t| jts"tdd S )NzjThe `child` argument must be an instance of `CharField`, as the hstore extension stores values as strings.)r   rl   rB   r  r  r   r  r   r3   r4   rl     s    zHStoreField.__init__)r/   r0   r1   r  r  rl   r   r3   r3   r   r4   r    s   r  c                       sD   e Zd ZdediZdZ fddZdd Zdd	 Zd
d Z	  Z
S )	JSONFieldr}   zValue must be valid JSON.Tc                    s<   | dd| _| dd | _| dd | _t jf | d S )NbinaryFencoderdecoder)r&  r  r  r  r   rl   r  r   r3   r4   rl     s    zJSONField.__init__c                 C   s@   t |r2| j|kr2G dd dt}||| j S || jtS )Nc                   @   s   e Zd Zdd ZdS )z'JSONField.get_value.<locals>.JSONStringc                 S   s   t | |}d|_|S r  )r)  r   is_json_string)r   r[   rb   r3   r3   r4   r     s    z/JSONField.get_value.<locals>.JSONString.__new__N)r/   r0   r1   r   r3   r3   r3   r4   
JSONString  s   r  )r'   r   r   r)  r   r-   )rk   rY   r  r3   r3   r4   r     s    zJSONField.get_valuec              	   C   sr   zJ| j st|ddr8t|tr&| }tj|| jdW S tj|| j	d W n" t
tfk
rl   | d Y nX |S )Nr  Fr   r}   )r  rM   rB   bytesdecoder)   loadsr  dumpsr  r  rP   r   r   r3   r3   r4   r      s    
zJSONField.to_internal_valuec                 C   s"   | j rtj|| jd}| }|S )Nr  )r  r)   r  r  encoder   r3   r3   r4   r     s    zJSONField.to_representation)r/   r0   r1   r   r   Z_is_jsonfieldrl   r   r   r   r   r3   r3   r   r4   r    s    r  c                       s(   e Zd ZdZ fddZdd Z  ZS )ReadOnlyFieldaw  
    A read-only field that simply returns the field value.

    If the field is a method with no parameters, the method will be called
    and its return value used as the representation.

    For example, the following would call `get_expiry_date()` on the object:

    class ExampleSerializer(Serializer):
        expiry_date = ReadOnlyField(source='get_expiry_date')
    c                    s   d|d< t  jf | d S )NTr   )r   rl   r  r   r3   r4   rl   "  s    zReadOnlyField.__init__c                 C   s   |S r6   r3   r   r3   r3   r4   r   &  s    zReadOnlyField.to_representation)r/   r0   r1   r2   rl   r   r   r3   r3   r   r4   r    s   r  c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )HiddenFieldaL  
    A hidden field does not take input from the user, or present any output,
    but it does populate a field in `validated_data`, based on its default
    value. This is particularly useful when we have a `unique_for_date`
    constraint on a pair of fields, as we need some way to include the date in
    the validated data.
    c                    s*   d|kst dd|d< t jf | d S )Nr:   zdefault is a required argument.Tr   )r   r   rl   r  r   r3   r4   rl   2  s    zHiddenField.__init__c                 C   s   t S r6   )r-   r  r3   r3   r4   r   7  s    zHiddenField.get_valuec                 C   s   |S r6   r3   r   r3   r3   r4   r   <  s    zHiddenField.to_internal_value)r/   r0   r1   r2   rl   r   r   r   r3   r3   r   r4   r  *  s   r  c                       s6   e Zd ZdZd	 fdd	Z fddZdd Z  ZS )
SerializerMethodFielda  
    A read-only field that get its representation from calling a method on the
    parent serializer class. The method called will be of the form
    "get_{field_name}", and should take a single argument, which is the
    object being serialized.

    For example:

    class ExampleSerializer(self):
        extra_info = SerializerMethodField()

        def get_extra_info(self, obj):
            return ...  # Calculate some data to return.
    Nc                    s(   || _ d|d< d|d< t jf | d S )Nr   r   Tr   )method_namer   rl   )rk   r  r   r   r3   r4   rl   O  s    zSerializerMethodField.__init__c                    s*   | j d krdj|d| _ t || d S )Nzget_{field_name})r   )r  rQ   r   r   r   r   r3   r4   r   U  s    
zSerializerMethodField.bindc                 C   s   t | j| j}||S r6   )rM   r   r  )rk   r[   methodr3   r3   r4   r   \  s    z'SerializerMethodField.to_representation)N)r/   r0   r1   r2   rl   r   r   r   r3   r3   r   r4   r  @  s   r  c                       sD   e Zd ZdZdediZ fddZdd Zdd	 Zd
d Z	  Z
S )
ModelFieldz
    A generic field that can be used against an arbitrary model field.

    This is used by `ModelSerializer` when dealing with custom model fields,
    that do not have a serializer field to be mapped to.
    r   r  c                    sZ   || _ |dd | _t jf | | jd k	rVt| jd | jd}| jt	| j|d d S )Nr   r#  r$  )
model_fieldr&  r   r   rl   r+   r   r   r'  r   )rk   r  r   r   r   r3   r4   rl   l  s    
zModelField.__init__c                 C   s2   | j j}|d k	r&|jj|j|S | j |S r6   )r  Zremote_fieldmodelZ_meta	get_fieldr   Z	to_python)rk   r   relr3   r3   r4   r   w  s    zModelField.to_internal_valuec                 C   s   |S r6   r3   )rk   rI   r3   r3   r4   rV   }  s    zModelField.get_attributec                 C   s$   | j |}t|r|S | j |S r6   )r  Zvalue_from_objectr   Zvalue_to_string)rk   rI   r[   r3   r3   r4   r     s    zModelField.to_representation)r/   r0   r1   r2   r   r   rl   r   rV   r   r   r3   r3   r   r4   r  a  s    r  )NN)|r   r  ri  rC   r>   r7  rC  r   collectionsr   collections.abcr   Zdjango.confr   Zdjango.core.exceptionsr   r   r   Zdjango.core.validatorsr   r   r	   r
   r   r   r   r   r   Zdjango.formsr   r  r   r  Zdjango.utilsr   Zdjango.utils.dateparser   r   r   r   Zdjango.utils.durationr   Zdjango.utils.encodingr   r   Zdjango.utils.formatsr   r   Zdjango.utils.ipv6r   Zdjango.utils.timezoner   Zdjango.utils.translationr    r   Zpytz.exceptionsr!   Zrest_frameworkr"   r#   r$   Zrest_framework.exceptionsr%   Zrest_framework.settingsr&   Zrest_framework.utilsr'   r(   r)   r*   Zrest_framework.utils.formattingr+   Zrest_framework.validatorsr,   r-   	Exceptionr5   rL   rV   r]   r`   rh   r{   r   r   r   r   r   r8  r   r   r   r   r   r   r   r   r  r  r/  r3  r4  r:  r;  rE  rL  r]  r_  rv  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r3   r3   r3   r4   <module>   s   ,

/$
   .2$%$ XC>"9)3O@/!