o
    ).hR                     @   s~  d dl Z d dlmZ d dlmZ d dlmZmZ d dlm	Z	 d dl
mZ d dlmZmZmZmZ d dlmZmZ d d	lmZ d d
lmZmZmZmZmZmZ d dlmZ d dl m!Z! d dl"m#Z# dd Z$G dd de%Z&G dd de'Z(G dd de)Z*G dd dZ+dZ,G dd deZ-G dd de-Z.G dd de-Z/G dd  d e-Z0G d!d" d"e0Z1G d#d$ d$e-Z2G d%d& d&eZ3dS )'    N)OrderedDict)parse)ImproperlyConfiguredObjectDoesNotExist)Manager)QuerySet)NoReverseMatchResolver404get_script_prefixresolve)	smart_str
uri_to_iri)gettext_lazy)Field	SkipFieldemptyget_attributeis_simple_callableiter_options)reverse)api_settings)htmlc                 C   s&   t || }t |d|}|t || juS )z4
    Determine if a method has been overridden.
    __func__)getattrr   )method_nameklassinstancemethoddefault_method r   W/var/www/supernova/superenvnew/lib/python3.10/site-packages/rest_framework/relations.pymethod_overridden   s   
r!   c                   @      e Zd ZdZdS )ObjectValueErrorz
    Raised when `queryset.get()` failed due to an underlying `ValueError`.
    Wrapping prevents calling code conflating this with unrelated errors.
    N__name__
__module____qualname____doc__r   r   r   r    r#          r#   c                   @   r"   )ObjectTypeErrorz
    Raised when `queryset.get()` failed due to an underlying `TypeError`.
    Wrapping prevents calling code conflating this with unrelated errors.
    Nr$   r   r   r   r    r*   $   r)   r*   c                       s8   e Zd ZdZ fddZdd Zedd ZdZ  Z	S )		Hyperlinkz
    A string like object that additionally has an associated name.
    We use this for hyperlinked URLs that may render as a named link
    in some contexts, or render as a plain URL in others.
    c                    s   t  | |}||_|S N)super__new__obj)clsurlr/   ret	__class__r   r    r.   1   s   zHyperlink.__new__c                 C   s   t | | jfS r,   )strnameselfr   r   r    __getnewargs__6   s   zHyperlink.__getnewargs__c                 C   s
   t | jS r,   )r5   r/   r7   r   r   r    r6   9   s   
zHyperlink.nameT)
r%   r&   r'   r(   r.   r9   propertyr6   is_hyperlink__classcell__r   r   r3   r    r+   +   s    
r+   c                   @   s    e Zd ZdZdd Zdd ZdS )PKOnlyObjectz
    This is a mock object, used for when we only need the pk of the object
    instance, but still want to return an object with a .pk attribute,
    in order to keep the same interface as a regular model instance.
    c                 C   s
   || _ d S r,   pk)r8   r?   r   r   r    __init__I      
zPKOnlyObject.__init__c                 C   s
   d| j  S )Nz%sr>   r7   r   r   r    __str__L   rA   zPKOnlyObject.__str__N)r%   r&   r'   r(   r@   rB   r   r   r   r    r=   C   s    r=   )	read_only
write_onlyrequireddefaultinitialsourcelabel	help_textstyleerror_messagesallow_emptyhtml_cutoffhtml_cutoff_textc                       s   e Zd ZdZdZdZ fddZ fddZedd Z	e
f fdd		Zd
d Zdd Z fddZdddZedd Zedd Zdd Zdd Z  ZS )RelatedFieldNc                    s   | d| j| _tj}|d urt|}| d|| _| d| jp$ttj| _t	dt
| s;| jd us;|ds;J d| jd urI|drIJ d| dd  | d	d  t jd
i | d S )NquerysetrN   rO   get_querysetrC   zfRelational field must provide a `queryset` argument, override `get_queryset`, or set read_only=`True`.zZRelational fields should not provide a `queryset` argument, when setting read_only=`True`.manyrM   r   )poprQ   r   HTML_SELECT_CUTOFFintrN   rO   _HTML_SELECT_CUTOFF_TEXTr!   rP   getr-   r@   )r8   kwargscutoff_from_settingsr3   r   r    r@   ^   s&   zRelatedField.__init__c                    s6   | ddr| j|i |S t j| g|R i |S )NrS   F)rT   	many_initr-   r.   )r0   argsrZ   r3   r   r    r.   w   s   zRelatedField.__new__c                 O   s>   d| |i |i}|D ]}|t v r|| ||< qtdi |S )aX  
        This method handles creating a parent `ManyRelatedField` instance
        when the `many=True` keyword argument is passed.

        Typically you won't need to override this method.

        Note that we're over-cautious in passing most arguments to both parent
        and child classes in order to try to cover the general case. If you're
        overriding this method you'll probably want something much simpler, eg:

        @classmethod
        def many_init(cls, *args, **kwargs):
            kwargs['child'] = cls()
            return CustomManyRelatedField(*args, **kwargs)
        child_relationNr   )MANY_RELATION_KWARGSManyRelatedField)r0   r]   rZ   list_kwargskeyr   r   r    r\   ~   s   zRelatedField.many_initc                    s   |dkrd }t  |S N )r-   run_validationr8   datar3   r   r    re      s   zRelatedField.run_validationc                 C   s    | j }t|ttfr| }|S r,   )rQ   
isinstancer   r   all)r8   rQ   r   r   r    rR      s   zRelatedField.get_querysetc                 C      dS NFr   r7   r   r   r    use_pk_only_optimization      z%RelatedField.use_pk_only_optimizationc                    sx   |   r6| jr6z%t|| jd d }|| jd }t|r!| }t|d|}t|dW S  ty5   Y nw t |S )Nr?   r>   )	rl   source_attrsr   serializable_valuer   r   r=   AttributeErrorr-   )r8   r   attribute_instancevaluer3   r   r    r      s   zRelatedField.get_attributec                    s>      }|d u r
i S |d ur|d | }t fdd|D S )Nc                    s    g | ]}  | |fqS r   )to_representationdisplay_value.0itemr7   r   r    
<listcomp>   s    z,RelatedField.get_choices.<locals>.<listcomp>)rR   r   )r8   cutoffrQ   r   r7   r    get_choices   s   zRelatedField.get_choicesc                 C      |   S r,   r{   r7   r   r   r    choices      zRelatedField.choicesc                 C      | j S r,   r~   r7   r   r   r    grouped_choices      zRelatedField.grouped_choicesc                 C      t | j| jd| j| jdS N)rz   )rz   cutoff_textr   r{   rN   rO   r7   r   r   r    r      
   zRelatedField.iter_optionsc                 C      t |S r,   r5   )r8   r   r   r   r    ru         zRelatedField.display_valuer,   )r%   r&   r'   rQ   rN   rO   r@   r.   classmethodr\   r   re   rR   rl   r   r{   r:   r~   r   r   ru   r<   r   r   r3   r    rP   Y   s&    



rP   c                       s(   e Zd ZdZ fddZdd Z  ZS )StringRelatedFieldzd
    A read only field that represents its targets using their
    plain string representation.
    c                    s   d|d< t  jdi | d S )NTrC   r   r-   r@   r8   rZ   r3   r   r    r@      s   zStringRelatedField.__init__c                 C   r   r,   r   r8   rs   r   r   r    rt      r   z$StringRelatedField.to_representation)r%   r&   r'   r(   r@   rt   r<   r   r   r3   r    r      s    r   c                       sL   e Zd ZedededdZ fddZdd Zd	d
 Zdd Z  Z	S )PrimaryKeyRelatedFieldThis field is required.z0Invalid pk "{pk_value}" - object does not exist.z8Incorrect type. Expected pk value, received {data_type}.)rE   does_not_existincorrect_typec                    s$   | dd | _t jdi | d S )Npk_fieldr   )rT   r   r-   r@   r   r3   r   r    r@      s   zPrimaryKeyRelatedField.__init__c                 C   rj   )NTr   r7   r   r   r    rl      rm   z/PrimaryKeyRelatedField.use_pk_only_optimizationc              	   C   s   | j d ur| j |}|  }zt|trt|j|dW S  ty.   | jd|d Y d S  tt	fyC   | jdt
|jd Y d S w )Nr>   r   )pk_valuer   	data_type)r   to_internal_valuerR   rh   bool	TypeErrorrY   r   fail
ValueErrortyper%   r8   rg   rQ   r   r   r    r     s   

z(PrimaryKeyRelatedField.to_internal_valuec                 C   s   | j d ur| j |jS |jS r,   )r   rt   r?   r   r   r   r    rt     s   
z(PrimaryKeyRelatedField.to_representation)
r%   r&   r'   rW   default_error_messagesr@   rl   r   rt   r<   r   r   r3   r    r      s    r   c                       sr   e Zd ZdZdZedededededdZd fd	d
	Zdd Zdd Z	dd Z
dd Zdd Z  ZS )HyperlinkedRelatedFieldr?   Nr   z!Invalid hyperlink - No URL match.z(Invalid hyperlink - Incorrect URL match.z*Invalid hyperlink - Object does not exist.z:Incorrect type. Expected URL string, received {data_type}.)rE   no_matchincorrect_matchr   r   c                    sj   |d ur|| _ | j d usJ d|d| j| _|d| j| _|dd | _t| _t jdi | d S )N%The `view_name` argument is required.lookup_fieldlookup_url_kwargformatr   )	view_namerT   r   r   r   r   r-   r@   r8   r   rZ   r3   r   r    r@      s   z HyperlinkedRelatedField.__init__c                 C   s
   | j dkS )Nr?   )r   r7   r   r   r    rl   /  rA   z0HyperlinkedRelatedField.use_pk_only_optimizationc                 C   s   || j  }| j|i}|  }z	|jdi |W S  ty1   ttt d }|	t d  t
yJ   ttt d }|	t d w )z
        Return the object corresponding to a matched URL.

        Takes the matched URL conf arguments, and should return an
        object instance, or raise an `ObjectDoesNotExist` exception.
              Nr   )r   r   rR   rY   r   r#   r5   sysexc_infowith_tracebackr   r*   )r8   r   	view_argsview_kwargslookup_valuelookup_kwargsrQ   excr   r   r    
get_object2  s   

z"HyperlinkedRelatedField.get_objectc                 C   s@   t |dr|jdv rdS t|| j}| j|i}| j||||dS )z
        Given an object, return the URL that hyperlinks to the object.

        May raise a `NoReverseMatch` if the `view_name` and `lookup_field`
        attributes are not configured to correctly match the URL conf.
        r?   rc   N)rZ   requestr   )hasattrr?   r   r   r   r   )r8   r/   r   r   r   r   rZ   r   r   r    get_urlF  s
   
zHyperlinkedRelatedField.get_urlc              
   C   s,  | j d}z|d}W n ty    | jdt|jd Y nw |r;t|j	}t
 }||r;d|t|d   }tt|}zt|}W n tyV   | d Y nw z
|j| j|}W n tym   | j}Y nw |j|krx| d z| |j|j|jW S  tttfy   | d Y d S w )	Nr   )zhttp:zhttps:r   r   /r   r   r   )contextrY   
startswithrq   r   r   r%   r   urlparsepathr
   lenr   unquoter   r	   versioning_schemeget_versioned_viewnamer   r   r]   rZ   r   r#   r*   )r8   rg   r   http_prefixprefixmatchexpected_viewnamer   r   r    r   U  s>   



z)HyperlinkedRelatedField.to_internal_valuec                 C   s   d| j v sJ d| jj | j d }| j d}|r%| jr%| j|kr%| j}z| || j||}W n! tyQ   d}|dv rJddd| }|d| 7 }t|| j w |d u rXd S t	||S )	Nr   zz`%s` requires the request in the serializer context. Add `context={'request': request}` when instantiating the serializer.r   zCould not resolve URL for hyperlinked relationship using view name "%s". You may have failed to include the related model in your API, or incorrectly configured the `lookup_field` attribute on this field.)rd   Nzthe empty stringNonez} WARNING: The value of the field on the model instance was %s, which may be why it didn't match any entries in your URL conf.)
r   r4   r%   rY   r   r   r   r   r   r+   )r8   rs   r   r   r1   msgvalue_stringr   r   r    rt   y  s4   

z)HyperlinkedRelatedField.to_representationr,   )r%   r&   r'   r   r   rW   r   r@   rl   r   r   r   rt   r<   r   r   r3   r    r     s    $r   c                       s*   e Zd ZdZd fdd	Zdd Z  ZS )HyperlinkedIdentityFieldz
    A read-only field that represents the identity URL for an object, itself.

    This is in contrast to `HyperlinkedRelatedField` which represents the
    URL of relationships to other objects.
    Nc                    s8   |d usJ dd|d< d|d< t  j|fi | d S )Nr   TrC   *rH   r   r   r3   r   r    r@     s   z!HyperlinkedIdentityField.__init__c                 C   rj   rk   r   r7   r   r   r    rl     s   z1HyperlinkedIdentityField.use_pk_only_optimizationr,   )r%   r&   r'   r(   r@   rl   r<   r   r   r3   r    r     s    r   c                       sD   e Zd ZdZededdZd fdd	Zdd	 Zd
d Z  Z	S )SlugRelatedFieldzm
    A read-write field that represents the target of the relationship
    by a unique 'slug' attribute.
    z/Object with {slug_name}={value} does not exist.zInvalid value.)r   invalidNc                    s,   |d usJ d|| _ t jdi | d S )Nz&The `slug_field` argument is required.r   )
slug_fieldr-   r@   )r8   r   rZ   r3   r   r    r@     s   zSlugRelatedField.__init__c              	   C   sl   |   }z|jdi | j|iW S  ty%   | jd| jt|d Y d S  ttfy5   | d Y d S w )Nr   )	slug_namers   r   r   )rR   rY   r   r   r   r   r   r   r   r   r   r    r     s   z"SlugRelatedField.to_internal_valuec                 C   s   t || jS r,   )r   r   )r8   r/   r   r   r    rt        z"SlugRelatedField.to_representationr,   )
r%   r&   r'   r(   rW   r   r@   r   rt   r<   r   r   r3   r    r     s    	r   c                       s   e Zd ZdZg Zg ZededdZdZdZ	d fdd	Z
dd	 Zd
d Zdd Zdd ZdddZedd Zedd Zdd Z  ZS )r`   a  
    Relationships with `many=True` transparently get coerced into instead being
    a ManyRelatedField with a child relationship.

    The `ManyRelatedField` class is responsible for handling iterating through
    the values and passing each one to the child relationship.

    This class is treated as private API.
    You shouldn't generally need to be using this class directly yourself,
    and should instead simply set 'many=True' on the relationship.
    z5Expected a list of items but got type "{input_type}".zThis list may not be empty.)
not_a_listr   Nc                    s   || _ |dd| _tj}|d urt|}|d|| _|d| jp&ttj	| _|d us1J dt
 j|i | | j jd| d d S )NrM   TrN   rO   z(`child_relation` is a required argument.rd   )
field_nameparent)r^   rT   rM   r   rU   rV   rN   rO   rW   rX   r-   r@   bind)r8   r^   r]   rZ   r[   r3   r   r    r@     s   zManyRelatedField.__init__c                 C   s@   t |r| j|vrt| jddrtS || jS || jtS )NpartialF)r   is_html_inputr   r   rootr   getlistrY   )r8   
dictionaryr   r   r    	get_value  s   

zManyRelatedField.get_valuec                    sV   t |ts
t|ds jdt|jd  js"t|dkr" d  fdd|D S )N__iter__r   )
input_typer   r   c                       g | ]} j |qS r   )r^   r   rv   r7   r   r    ry         
z6ManyRelatedField.to_internal_value.<locals>.<listcomp>)rh   r5   r   r   r   r%   rM   r   rf   r   r7   r    r   
  s   

z"ManyRelatedField.to_internal_valuec              
   C   s   t |dr|jd u rg S zt|| j}W nF ttfyZ } z8| jtur-|  W  Y d }~S | j	r7W Y d }~d S | j
s=t djt|j| j| jjj|jj|d}t||d }~ww t |drd| S |S )Nr?   zGot {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_typefield
serializerr   r   ri   )r   r?   r   ro   KeyErrorrq   rF   r   get_default
allow_nullrE   r   r   r   r%   r   r   r4   ri   )r8   r   relationshipr   r   r   r   r    r     s0   
zManyRelatedField.get_attributec                    s    fdd|D S )Nc                    r   r   )r^   rt   )rw   rs   r7   r   r    ry   5  r   z6ManyRelatedField.to_representation.<locals>.<listcomp>r   )r8   iterabler   r7   r    rt   4  s   
z"ManyRelatedField.to_representationc                 C   s   | j |S r,   )r^   r{   )r8   rz   r   r   r    r{   :  r   zManyRelatedField.get_choicesc                 C   r|   r,   r}   r7   r   r   r    r~   =  r   zManyRelatedField.choicesc                 C   r   r,   r   r7   r   r   r    r   A  r   z ManyRelatedField.grouped_choicesc                 C   r   r   r   r7   r   r   r    r   E  r   zManyRelatedField.iter_optionsr,   )r%   r&   r'   r(   rG   default_empty_htmlrW   r   rN   rO   r@   r   r   r   rt   r{   r:   r~   r   r   r<   r   r   r3   r    r`     s(    


r`   )4r   collectionsr   urllibr   django.core.exceptionsr   r   django.db.modelsr   django.db.models.queryr   django.urlsr   r	   r
   r   django.utils.encodingr   r   django.utils.translationr   rW   rest_framework.fieldsr   r   r   r   r   r   rest_framework.reverser   rest_framework.settingsr   rest_framework.utilsr   r!   r   r#   r   r*   r5   r+   r=   r_   rP   r   r   r   r   r   r`   r   r   r   r    <module>   s8     	 ! 