U
    ڲg                    @   sD  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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 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l2m3Z4 zd dl5Z5W n e6k
rR   dZ5Y nX d dl7m8Z8 d dl9m:Z: d dl;m<Z<mZ d dl=m>Z> d dl?m@Z@mAZAmBZBmCZC d dlDmEZE d dlFmGZG d dlHmIZI G dd dZJG dd deKZLdd ZMdd  ZNd!d" ZOd#d$ ZPdqd%d&ZQd'd( ZRG d)d* d*ZSG d+d, d,ZTG d-d. d.eKZUeVeWd/ZXd0ZYd1ZZd2Z[d3Z\d4Z]G d5d6 d6Z^G d7d8 d8e^Z_G d9d: d:e^Z`G d;d< d<e`ZaG d=d> d>e`ZbG d?d@ d@e`ZcG dAdB dBe`ZdG dCdD dDe^ZeG dEdF dFe`ZfG dGdH dHe^ZgG dIdJ dJe^ZhG dKdL dLe^ZiG dMdN dNe^ZjG dOdP dPe^ZkG dQdR dRe^ZlG dSdT dTe^ZmG dUdV dVe^ZnG dWdX dXenZoG dYdZ dZenZG d[d\ d\e^ZpG d]d^ d^epZG d_d` d`e^ZqG dadb dbe^ZrG dcdd dde^ZsG dedf dfesZtG dgdh dhe^ZuG didj dje^ZvG dkdl dle^ZwG dmdn dne^ZxG dodp dpe^ZydS )r    N)Mapping)Enum)settings)ObjectDoesNotExist)ValidationError)EmailValidatorMaxLengthValidatorMaxValueValidatorMinLengthValidatorMinValueValidatorProhibitNullCharactersValidatorRegexValidatorURLValidator)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)gettext_lazy)ISO_8601)ip_address_validators)ErrorDetailr   )api_settings)htmlhumanize_datetimejsonrepresentation)lazy_format)valid_datetime)$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__ r0   r0   9/tmp/pip-unpacked-wheel-11h17kvo/rest_framework/fields.pyr*   0   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+   r0   r0   r0   r1   r2   :   s   r2   c                 C   sh   t | sdS t| rtdt| sBt| sBt| tjsBdS t	| }|j
 }tdd |D S )zC
    True if the object is a callable that takes no arguments.
    FzkBuilt-in function signatures are not inspectable. Wrap the function call in a simple, pure Python function.c                 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paramr0   r0   r1   	<genexpr>T   s
   
z%is_simple_callable.<locals>.<genexpr>)callableinspect	isbuiltinr2   
isfunctionismethod
isinstance	functoolspartial	signature
parametersvaluesall)objsigparamsr0   r0   r1   is_simple_callableB   s    
 

rJ   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: {})	r@   r   getattrr   rJ   AttributeErrorKeyError
ValueErrorformat)instanceattrsattrexcr0   r0   r1   get_attribute\   s    



$rT   c                 C   sV   i }| D ]H}t |ttfs$|||< q|\}}t |ttfrHt|||< 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@   listtupleto_choices_dict)choicesretchoicekeyvaluer0   r0   r1   rW   w   s    

rW   c                 C   sH   i }|   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'}
    )itemsr@   dict)rX   rY   r[   r\   sub_key	sub_valuer0   r0   r1   flatten_choices_dict   s    

ra   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 r3   label)selfrc   r0   r0   r1   __init__   s    z/iter_options.<locals>.StartOptionGroup.__init__Nr,   r-   r.   start_option_groupend_option_groupre   r0   r0   r0   r1   StartOptionGroup   s   ri   c                   @   s   e Zd ZdZdZdS )z$iter_options.<locals>.EndOptionGroupFTN)r,   r-   r.   rg   rh   r0   r0   r0   r1   EndOptionGroup   s   rj   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 r3   r\   display_textdisabled)rd   r\   rl   rm   r0   r0   r1   re      s    z%iter_options.<locals>.Option.__init__N)Frf   r0   r0   r0   r1   Option   s   rn   r   rb   )r\   rl      )countzn/aTrk   N)r]   r@   r^   rO   )grouped_choicescutoffcutoff_textri   rj   rn   rp   r[   r\   r_   r`   r0   r0   r1   iter_options   s(    	



rt   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 ru   r!   rI   messageru   r8   errorrx   r0   r1   
<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 rw   ry   r{   rx   r0   r1   r}      s   z/get_error_detail.<locals>.<dictcomp>.<listcomp>r0   )r8   kerrorsrx   r0   r1   
<dictcomp>   s
    
z$get_error_detail.<locals>.<dictcomp>)rK   
error_dictrL   Z
error_listr]   )exc_infor   r0   rx   r1   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 r3   r7   )rd   r7   r0   r0   r1   re      s    zCreateOnlyDefault.__init__c                 C   sF   |j jd k	}|rt t| jr@t| jddr8| |S |  S | jS )Nrequires_contextF)parentrP   	SkipFieldr;   r7   rK   )rd   serializer_fieldZ	is_updater0   r0   r1   __call__   s    

zCreateOnlyDefault.__call__c                 C   s   d| j jt| jf S )Nz%s(%s))	__class__r,   reprr7   rd   r0   r0   r1   __repr__  s    zCreateOnlyDefault.__repr__N)r,   r-   r.   r/   r   re   r   r   r0   r0   r0   r1   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)rd   r   r0   r0   r1   r   	  s    zCurrentUserDefault.__call__c                 C   s   d| j j S )Nz%s())r   r,   r   r0   r0   r1   r     s    zCurrentUserDefault.__repr__N)r,   r-   r.   r   r   r   r0   r0   r0   r1   r     s   r   c                   @   s   e Zd ZdS )r   N)r,   r-   r.   r0   r0   r0   r1   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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/d0 Z  Z S )1Fieldr   zThis field is required.zThis field may not be null.)requirednullNF)	read_only
write_onlyr   r7   initialsourcerc   	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 )Nro   default_error_messages)r   _creation_counterr*   AssertionErrorNOT_READ_ONLY_WRITE_ONLYNOT_READ_ONLY_REQUIREDNOT_REQUIRED_DEFAULTr   USE_READONLYFIELDr   r   r   r7   r   r   rc   r   r   r   default_empty_htmlrU   r   
field_namer   reversed__mro__updaterK   r   )rd   r   r   r   r7   r   r   rc   r   r   r   r   r   messagesclsr0   r0   r1   re   +  s<    

zField.__init__c                 O   s   | S r3   r0   )r   argskwargsr0   r0   r1   __class_getitem__Z  s    zField.__class_getitem__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   rc   replace
capitalizesource_attrssplitrd   r   r   r0   r0   r1   bind]  s    	


z
Field.bindc                 C   s   t | ds|  | _| jS )N_validators)hasattrget_validatorsr   r   r0   r0   r1   r     s    

zField.validatorsc                 C   s
   || _ d S r3   )r   )rd   r   r0   r0   r1   r     s    c                 C   s
   t | jS r3   )rU   default_validatorsr   r0   r0   r1   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   r0   r0   r1   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.
        rB   Fr   allow_blankN)
r#   is_html_inputr   rK   rootr*   r   r   r   get)rd   
dictionaryrY   r0   r0   r1   	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fieldrP   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   rP   rS   )rT   r   r2   rO   r   r   r,   r   typerM   rL   r7   r*   get_defaultr   r   r   )rd   rP   rS   msgr0   r0   r1   rT     s4    


zField.get_attributec                 C   sN   | j tkst| jddrt t| j rHt| j ddr@|  | 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.
        rB   Fr   )r7   r*   rK   r   r   r;   r   r0   r0   r1   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.
        TrB   Fr   Nr   r   )FNTN)
r   r   r*   rK   r   r   r   failr   r   rd   datar0   r0   r1   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)rd   r   Zis_empty_valuer\   r0   r0   r1   run_validation  s    


zField.run_validationc                 C   s   g }| j D ]}z$t|ddr(|||  n|| W q
 tk
rn } zt|jtrR ||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   FN)	r   rK   r   r@   detailr^   extendDjangoValidationErrorr   )rd   r\   r   	validatorrS   r0   r0   r1   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NotImplementedErrorrO   r   r,   r   r   r0   r0   r1   r   6  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   rd   r\   r0   r0   r1   to_representationC  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[   rx   N)r   rM   r   r,   MISSING_ERROR_MESSAGErO   r   r   )rd   r[   r   r   r   Zmessage_stringr0   r0   r1   r   N  s    z
Field.failc                 C   s   | }|j dk	r|j }q|S )zB
        Returns the top-level serializer for this field.
        N)r   )rd   r   r0   r0   r1   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)rK   r   r   r0   r0   r1   r   e  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   r   r   rP   r   r0   r1   r   l  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 r0   )r@   
REGEX_TYPEcopydeepcopyr8   itemr0   r0   r1   r}   ~  s   z&Field.__deepcopy__.<locals>.<listcomp>c                    s*   i | ]"\}}||d kr"t | n|qS ))r   regex)r   r   )r8   r[   r\   memor0   r1   r     s    z&Field.__deepcopy__.<locals>.<dictcomp>)r   r   r]   r   )rd   r   r   r   r0   r   r1   __deepcopy__v  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   r0   r0   r1   r     s    zField.__repr__)!r,   r-   r.   r   r   r   r   r*   r   r   re   r   r   propertyr   setterr   r   r   rT   r   r   r   r   r   r   r   r   r   r   r   r   __classcell__r0   r0   r   r1   r      sV          /$

	)!
	

r   c                	       s   e Zd ZdediZdZdZdddddd	d
dhZdddddddddh	ZdddhZ	 fddZ
edd Zdd Zdd Z  ZS )BooleanFieldrv   zMust be a valid boolean.Ftyyestrueon1ro   Tfnnofalseoff0r   g        r   r   Nc                    s*   | ddrd | _d | _t jf | d S )Nr   F)r   r   r   r   re   rd   r   r   r0   r1   re     s    zBooleanField.__init__c                 C   s   t | tr|  S | S r3   )r@   strlowerr\   r0   r0   r1   _lower_if_str  s    
zBooleanField._lower_if_strc              	   C   s   t tf | || jkr*W 5 Q R  dS | || jkrHW 5 Q R  dS | || jkrl| jrlW 5 Q R  d S W 5 Q R X | jd|d d S )NTFrv   input)	
contextlibsuppress	TypeErrorr  TRUE_VALUESFALSE_VALUESNULL_VALUESr   r   r   r0   r0   r1   r     s    zBooleanField.to_internal_valuec                 C   sJ   |  || jkrdS |  || jkr(dS |  || jkrB| jrBd S t|S )NTF)r  r  r	  r
  r   boolr   r0   r0   r1   r     s    zBooleanField.to_representation)r,   r-   r.   r   r   r   r   r  r	  r
  re   staticmethodr  r   r   r   r0   r0   r   r1   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.)rv   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  rz   r  )popr   r  r  r  r   re   r'   r   r   appendr   r
   r   r)   rd   r   rz   r   r0   r1   re     s"    

zCharField.__init__c                    s>   |dks| j r2t| dkr2| js.| d dS t |S )Nr   r  )r  r   stripr   r   r   r   r   r   r0   r1   r     s
    
zCharField.run_validationc                 C   s>   t |tst |tttfs$| d t|}| jr:| S |S )Nrv   )r@   r  r   intfloatr   r  r  rd   r   r\   r0   r0   r1   r     s    
zCharField.to_internal_valuec                 C   s   t |S r3   )r   r   r0   r0   r1   r      s    zCharField.to_representation)r,   r-   r.   r   r   r   re   r*   r   r   r   r   r0   r0   r   r1   r    s   
	r  c                       s(   e Zd ZdediZ fddZ  ZS )
EmailFieldrv   zEnter a valid email address.c                    s.   t  jf | t| jd d}| j| d S Nrv   r  )r   re   r   r   r   r  rd   r   r   r   r0   r1   re   	  s    zEmailField.__init__r,   r-   r.   r   r   re   r   r0   r0   r   r1   r    s    r  c                       s(   e Zd ZdediZ fddZ  ZS )
RegexFieldrv   z/This value does not match the required pattern.c                    s0   t  jf | t|| jd d}| j| d S r  )r   re   r   r   r   r  )rd   r   r   r   r   r0   r1   re     s    zRegexField.__init__r   r0   r0   r   r1   r!    s    r!  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.)rv   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]+\Zr#  r  z^[-a-zA-Z0-9_]+$rv   )
r   re   allow_unicoder   recompileUNICODEr   r   r  )rd   r$  r   r   r   r0   r1   re      s    zSlugField.__init__)Fr   r0   r0   r   r1   r"    s   r"  c                       s(   e Zd ZdediZ fddZ  ZS )URLFieldrv   zEnter a valid URL.c                    s.   t  jf | t| jd d}| j| d S r  )r   re   r   r   r   r  r  r   r0   r1   re   /  s    zURLField.__init__r   r0   r0   r   r1   r(  *  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urnrv   zMust be a valid UUID.c                    sB   | dd| _| j| jkr0tdd| jt jf | d S )NrO   r*  z;Invalid format for uuid representation. Must be one of "{}"z", ")r  uuid_formatvalid_formatsrN   rO   joinr   re   r   r   r0   r1   re   <  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+  rv   r  )r@   uuidUUIDr  r   r   rN   r   r0   r0   r1   r   E  s    

zUUIDField.to_internal_valuec                 C   s"   | j dkrt|S t|| j S d S )Nr*  )r,  r   rK   r   r0   r0   r1   r   R  s    
zUUIDField.to_representation)
r,   r-   r.   r-  r   r   re   r   r   r   r0   r0   r   r1   r)  5  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 GenericIPAddressFieldrv   z#Enter a valid IPv4 or IPv6 address.bothc                    s@   |  | _| jdk| _t jf | t|| j}| j| d S )Nr3  )r   protocolunpack_ipv4r   re   r    r   r   )rd   r4  r   r   r   r0   r1   re   `  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 )Nrv   r  :)r3  Zipv6)	r@   r   r   r4  r   r5  r   r   r   r   r   r0   r1   r   g  s    

z IPAddressField.to_internal_value)r3  )	r,   r-   r.   r/   r   r   re   r   r   r0   r0   r   r1   r2  Y  s    r2  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.)rv   	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 Nr;  r<  r;  r  r<  r  r;  r<  r   re   r'   r   r   r  r	   r   r  r   r0   r1   re     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 )Nr=  r   rv   )
r@   r   lenMAX_STRING_LENGTHr   r  
re_decimalsubrN   r  r   r0   r0   r1   r     s    
zIntegerField.to_internal_valuec                 C   s   t |S r3   r/  r   r0   r0   r1   r     s    zIntegerField.to_representation)r,   r-   r.   r   r   rD  r%  r&  rE  re   r   r   r   r0   r0   r   r1   r7  w  s   

r7  c                       sT   e Zd Zed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.r8  r9  r:  z+Integer value too large to convert to float)rv   r;  r<  r=  overflowr>  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 r?  rB  r  r   r0   r1   re     s    

zFloatField.__init__c              	   C   sp   t |tr"t|| jkr"| d z
t|W S  ttfk
rN   | d Y n tk
rj   | d Y nX d S )Nr=  rv   rI  )	r@   r   rC  rD  r   r  r  rN   OverflowErrorr   r0   r0   r1   r     s    

zFloatField.to_internal_valuec                 C   s   t |S r3   )r  r   r0   r0   r1   r     s    zFloatField.to_representation)
r,   r-   r.   r   r   rD  re   r   r   r   r0   r0   r   r1   rG    s   rG  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 )DecimalFieldrH  r8  r9  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.r:  )rv   r;  r<  
max_digitsmax_decimal_placesmax_whole_digitsr=  r>  NFc	                    sh  || _ || _|| _|| _|d k	r&|| _| jr2d| _|| _|| _| jd k	r`t| jtj	s`t
d | jd k	rt| jtj	st
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	r$t| jd | jd}
| jt| j|
d |d k	r^d	d
 tt D }||ks^td||f || _d S )NTz'max_value should be a Decimal instance.z'min_value should be a Decimal instance.r;  r@  r  r<  rA  c                 S   s   g | ]\}}| d r|qS )ZROUND_)
startswith)r8   r~   vr0   r0   r1   r}     s     
 z)DecimalField.__init__.<locals>.<listcomp>z=Invalid rounding option %s. Valid values for rounding are: %s)rL  decimal_placeslocalizenormalize_outputcoerce_to_stringr;  r<  r@   decimalDecimalwarningswarnrN  r   re   r'   r   r   r  r	   r   varsr]   r   rounding)rd   rL  rQ  rT  r;  r<  rR  rZ  rS  r   rz   Zvalid_roundingsr   r0   r1   re     sD    




zDecimalField.__init__c                    s&   t | dkr| jrdS t |S )Nr   r   )r   r  r   r   r   r   r   r0   r1   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.
        r=  rv   ZInfz-Inf)r   r  rR  r   rC  rD  r   rU  rV  DecimalExceptionis_nanquantizevalidate_precisionr  r0   r0   r1   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   NrL  )rL  rM  )rM  rN  )rN  )as_tuplerC  absrL  r   rQ  rN  )rd   r\   signZ
digittupleexponentZtotal_digitsZwhole_digitsrQ  r0   r0   r1   r^    s&    
zDecimalField.validate_precisionc                 C   sx   t | dtj}|d kr"|rdS d S t|tjs@tt| }| |}| j	rX|
 }|s`|S | jrnt|S d|S )NrT  r   z{:f})rK   r"   ZCOERCE_DECIMAL_TO_STRINGr@   rU  rV  r   r  r]  rS  	normalizerR  r   rO   )rd   r\   rT  Z	quantizedr0   r0   r1   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)rZ  r   )	rQ  rU  
getcontextr   rL  precr]  rV  rZ  )rd   r\   r   r0   r0   r1   r]  T  s    

zDecimalField.quantize)NNNFNF)r,   r-   r.   r   r   rD  re   r   r   r^  r   r]  r   r0   r0   r   r1   rK    s&   	      )#rK  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.)rv   date
make_awarerI  Nc                    s<   |t k	r|| _|d k	r|| _|d k	r*|| _t jf | d S r3   )r*   rO   input_formatsr   r   re   )rd   rO   ri  default_timezoner   r   r0   r1   re   p  s    zDateTimeField.__init__c              
   C   s   t | dr| jn|  }|dk	rt|rVz||W S  tk
rT   | d Y nX z(t||}t|sz| jd|d |W S  t	k
r } z(t
rt|t
jjr| jd|d |W 5 d}~X Y qX n"|dkrt|rt|tjj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   NrI  rh  r   )r   r   rj  Zis_aware
astimezonerJ  r   rh  r(   	Exceptionpytzr@   
exceptionsZInvalidTimeErrorZ
make_naivedatetimeutc)rd   r\   Zfield_timezonedter0   r0   r1   enforce_timezoney  s&    
zDateTimeField.enforce_timezonec                 C   s   t jrt S d S r3   )r   ZUSE_TZr   Zget_current_timezoner   r0   r0   r1   rj    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}t	t
t^ | tkrt|}|d k	r| |W  5 Q R    S | ||}| |W  5 Q R    S Q R X qJt|}| jd|d d S )Nri  rg  rv   rO   )rK   r"   ZDATETIME_INPUT_FORMATSr@   ro  rg  r   rs  r  r  rN   r  r   r   r   datetime_parserr$   Zdatetime_formatsrd   r\   ri  Zinput_formatparsedZhumanized_formatr0   r0   r1   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 )NrO   z+00:00iZ)rK   r"   ZDATETIME_FORMATr@   r   rs  r   r   	isoformatendswithstrftimerd   r\   Zoutput_formatr0   r0   r1   r     s    

zDateTimeField.to_representation)r,   r-   r.   r   r   ro  strptimeru  r*   re   rs  rj  r   r   r   r0   r0   r   r1   rf  g  s   	rf  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.)rv   ro  Nc                    s.   |t k	r|| _|d k	r|| _t jf | d S r3   r*   rO   ri  r   re   rd   rO   ri  r   r   r0   r1   re     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 )Nri  ro  rv   rt  )rK   r"   ZDATE_INPUT_FORMATSr@   ro  r   rg  r   r   r   rN   r  ru  r$   Zdate_formatsrv  r0   r0   r1   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 )NrO   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.)rK   r"   ZDATE_FORMATr@   r   ro  r   r   r   ry  r{  r|  r0   r0   r1   r     s    zDateField.to_representationr,   r-   r.   r   r   ro  r}  ru  r*   re   r   r   r   r0   r0   r   r1   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 )
	TimeFieldrv   zBTime has wrong format. Use one of these formats instead: {format}.Nc                    s.   |t k	r|| _|d k	r|| _t jf | d S r3   r  r  r   r0   r1   re   
  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 )Nri  rv   rt  )rK   r"   ZTIME_INPUT_FORMATSr@   ro  timer   r   r   rN   r  ru  r$   Ztime_formatsr   rv  r0   r0   r1   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   rO   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.)rK   r"   ZTIME_FORMATr@   r   ro  r   r   r   ry  r{  r|  r0   r0   r1   r   +  s    zTimeField.to_representationr  r0   r0   r   r1   r    s    r  c                       sJ   e Zd Zed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}.r8  r9  z=The number of days must be between {min_days} and {max_days}.)rv   r;  r<  rI  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 r?  rB  r  r   r0   r1   re   J  s    

zDurationField.__init__c                 C   sp   t |tjr|S ztt|}W n0 tk
rP   | jdtjjjtjj	jd Y nX |d k	r^|S | jddd d S )NrI  )Zmin_daysZmax_daysrv   z[DD] [HH:[MM:]]ss[.uuuuuu]rt  )
r@   ro  	timedeltar   r   rJ  r   mindaysmax)rd   r\   rw  r0   r0   r1   r   W  s    "zDurationField.to_internal_valuec                 C   s   t |S r3   r   r   r0   r0   r1   r   b  s    zDurationField.to_representation	r,   r-   r.   r   r   re   r   r   r   r0   r0   r   r1   r  B  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)rX   r  r  r  r   r   re   )rd   rX   r   r   r0   r1   re   o  s
    zChoiceField.__init__c                 C   sl   |dkr| j rdS t|tr4t|t|jkr4|j}z| jt| W S  tk
rf   | jd|d Y nX d S )Nr   r  r  )r   r@   r   r   r\   choice_strings_to_valuesrM   r   r   r0   r0   r1   r   x  s    zChoiceField.to_internal_valuec                 C   s@   |dkr|S t |tr.t|t|jkr.|j}| jt||S )N)r   N)r@   r   r   r\   r  r   r   r0   r0   r1   r     s
    zChoiceField.to_representationc                 C   s   t | j| j| jdS )zP
        Helper method for use with templates rendering select widgets.
        )rr   rs   )rt   rq   r  r  r   r0   r0   r1   rt     s
    zChoiceField.iter_optionsc                 C   s   | j S r3   )_choicesr   r0   r0   r1   _get_choices  s    zChoiceField._get_choicesc                 C   s,   t || _t| j| _dd | jD | _d S )Nc                 S   s<   i | ]4}t |tr.t|t|jkr.t|jnt||qS r0   )r@   r   r   r\   )r8   r[   r0   r0   r1   r     s    , z,ChoiceField._set_choices.<locals>.<dictcomp>)rW   rq   ra   r  rX   r  )rd   rX   r0   r0   r1   _set_choices  s
    
zChoiceField._set_choices)r,   r-   r.   r   r   r  r  re   r   r   rt   r  r  r   rX   r   r0   r0   r   r1   r  h  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   re   r   r   r0   r1   re     s    zMultipleChoiceField.__init__c                 C   s@   | j |krt| jddrtS t|r2|| j S || j tS )NrB   F)r   rK   r   r*   r#   r   getlistr   rd   r   r0   r0   r1   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 r0   )r   r  r   r   )r   rd   r0   r1   	<setcomp>  s   z8MultipleChoiceField.to_internal_value.<locals>.<setcomp>)r@   r   r   r   r   r,   r  rC  r   r   r   r1   r     s    
z%MultipleChoiceField.to_internal_valuec                    s    fdd|D S )Nc                    s   h | ]} j t||qS r0   )r  r   r   r   r   r0   r1   r    s    z8MultipleChoiceField.to_representation.<locals>.<setcomp>r0   r   r0   r   r1   r     s    
z%MultipleChoiceField.to_representation)r,   r-   r.   r   r   r   re   r   r   r   r   r0   r0   r   r1   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           	         s8   t ||||||d}|j|d< ||d< t jf | d S )N)match	recursiveallow_filesallow_foldersr   rX   r   )DjangoFilePathFieldrX   r   re   )	rd   pathr  r  r  r  r   r   r   r   r0   r1   re     s        
zFilePathField.__init__)NFTFNr   r0   r0   r   r1   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   rv   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   re   r   r   r0   r1   re     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 )Nrv   r  r*   r  )r  length)namesizerL   r   r  r  rC  )rd   r   	file_name	file_sizer0   r0   r1   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   )	rK   r"   ZUPLOADED_FILES_USE_URLurlrL   r   r   Zbuild_absolute_urir  )rd   r\   r  r  r   r0   r0   r1   r     s    

zFileField.to_representationr  r0   r0   r   r1   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   re   r   r   r0   r1   re     s    zImageField.__init__c                    s&   t  |}|  }| j|_||S r3   )r   r   r  r   clean)rd   r   Zfile_objectZdjango_fieldr   r0   r1   r     s    zImageField.to_internal_value)r,   r-   r.   r   r   re   r   r   r0   r0   r   r1   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   re   r   r   r   r   r0   r1   re   ,  s    z_UnvalidatedField.__init__c                 C   s   |S r3   r0   r   r0   r0   r1   r   1  s    z#_UnvalidatedField.to_internal_valuec                 C   s   |S r3   r0   r   r0   r0   r1   r   4  s    z#_UnvalidatedField.to_representation)r,   r-   r.   re   r   r   r   r0   r0   r   r1   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   re   r   r'   r   r   r  r   r
   r  r   r0   r1   re   B  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 )NrB   Fr   )prefixr7   )
r   rK   r   r*   r#   r   r  rC  parse_html_listr   )rd   r   valr0   r0   r1   r   W  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  r@   r   r   r   r   r   r,   r  rC  run_child_validationr   r0   r0   r1   r   f  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 r3   )r  r   r   r   r0   r1   r}   v  s     z/ListField.to_representation.<locals>.<listcomp>r0   r   r0   r   r1   r   r  s    zListField.to_representationc                 C   s   g }i }t |D ]x\}}z|| j| W q tk
rZ } z|j||< W 5 d }~X Y q tk
r } zt|||< W 5 d }~X Y qX q|s|S t|d S r3   )	enumerater  r  r   r   r   r   r   )rd   r   resultr   idxr   rr  r0   r0   r1   r  x  s     zListField.run_child_validationr,   r-   r.   r  r  r   r   r   re   r   r   r   r  r   r0   r0   r   r1   r  8  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   re   r   r   r   r0   r1   re     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  r0   r0   r1   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  r@   r^   r   r   r,   r  rC  r  r   r0   r0   r1   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 r3   )r   r  r   )r8   r[   r  r   r0   r1   r     s    z/DictField.to_representation.<locals>.<dictcomp>)r]   r   r0   r   r1   r     s    
zDictField.to_representationc                 C   sx   i }i }|  D ]R\}}t|}z| j|||< W q tk
r` } z|j||< W 5 d }~X Y qX q|sl|S t|d S r3   )r]   r   r  r   r   r   )rd   r   r  r   r[   r\   rr  r0   r0   r1   r    s    zDictField.run_child_validationr  r0   r0   r   r1   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   re   r@   r  r  r   r   r   r0   r1   re     s    zHStoreField.__init__)r,   r-   r.   r  r  re   r   r0   r0   r   r1   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 )	JSONFieldrv   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   re   r   r   r0   r1   re     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\   rY   r0   r0   r1   r     s    z/JSONField.get_value.<locals>.JSONString.__new__N)r,   r-   r.   r   r0   r0   r0   r1   
JSONString  s   r  )r#   r   r   r   r   r*   )rd   r   r  r0   r0   r1   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   rv   )r  rK   r@   bytesdecoder%   loadsr  dumpsr  r  rN   r   r   r0   r0   r1   r     s    
zJSONField.to_internal_valuec                 C   s"   | j rtj|| jd}| }|S )Nr  )r  r%   r  r  encoder   r0   r0   r1   r     s    zJSONField.to_representation)r,   r-   r.   r   r   Z_is_jsonfieldre   r   r   r   r   r0   r0   r   r1   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   re   r   r   r0   r1   re     s    zReadOnlyField.__init__c                 C   s   |S r3   r0   r   r0   r0   r1   r     s    zReadOnlyField.to_representation)r,   r-   r.   r/   re   r   r   r0   r0   r   r1   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 )Nr7   zdefault is a required argument.Tr   )r   r   re   r   r   r0   r1   re   !  s    zHiddenField.__init__c                 C   s   t S r3   )r*   r  r0   r0   r1   r   &  s    zHiddenField.get_valuec                 C   s   |S r3   r0   r   r0   r0   r1   r   +  s    zHiddenField.to_internal_value)r,   r-   r.   r/   re   r   r   r   r0   r0   r   r1   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(Serializer):
        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   re   )rd   r  r   r   r0   r1   re   ?  s    zSerializerMethodField.__init__c                    s*   | j d krdj|d| _ t || d S )Nzget_{field_name})r   )r  rO   r   r   r   r   r0   r1   r   E  s    
zSerializerMethodField.bindc                 C   s   t | j| j}||S r3   )rK   r   r  )rd   r\   methodr0   r0   r1   r   L  s    z'SerializerMethodField.to_representation)N)r,   r-   r.   r/   re   r   r   r   r0   r0   r   r1   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   re   r'   r   r   r  r   )rd   r  r   rz   r   r0   r1   re   \  s    
zModelField.__init__c                 C   s2   | j j}|d k	r&|jj|j|S | j |S r3   )r  Zremote_fieldmodelZ_meta	get_fieldr   Z	to_python)rd   r   relr0   r0   r1   r   g  s    zModelField.to_internal_valuec                 C   s   |S r3   r0   )rd   rG   r0   r0   r1   rT   m  s    zModelField.get_attributec                 C   s$   | j |}t|r|S | j |S r3   )r  Zvalue_from_objectr   Zvalue_to_string)rd   rG   r\   r0   r0   r1   r   r  s    zModelField.to_representation)r,   r-   r.   r/   r   r   re   r   rT   r   r   r0   r0   r   r1   r  Q  s    r  )NN)zr  r   ro  rU  rA   r<   r%  r0  rW  collections.abcr   enumr   Zdjango.confr   Zdjango.core.exceptionsr   r   r   Zdjango.core.validatorsr   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.translationr   r   rm  ImportErrorZrest_frameworkr   Zrest_framework.compatr    Zrest_framework.exceptionsr!   Zrest_framework.settingsr"   Zrest_framework.utilsr#   r$   r%   r&   Zrest_framework.utils.formattingr'   Zrest_framework.utils.timezoner(   Zrest_framework.validatorsr)   r*   rl  r2   rJ   rT   rW   ra   rt   r   r   r   r   r   r&  r   r   r   r   r   r   r   r   r  r  r!  r"  r(  r)  r2  r7  rG  rK  rf  r~  r  r  r  r  r  r  r  r  r  r  r  r  r  r  r0   r0   r0   r1   <module>   s   (


/
  u?2$%' %ZC>&<)3Q@/"