
^Q\d                 @   s  d  d l  m Z 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 d  d l m Z m Z m Z m Z m Z m Z Gd d	   d	 e  Z e   Z e j Gd
 d   d e   Z e j Gd d   d e   Z Gd d   d e  Z d S)    )absolute_importunicode_literals)OrderedDict)islice)six)SafeData)title)AccessorAttributeDictOrderByOrderByTuplecall_with_appropriatecomputed_valuesc               @   s:   e  Z d  Z d Z d d   Z d d   Z d d   Z d S)	Libraryz"
    A collection of columns.
    c             C   s   g  |  _  d  S)N)columns)self r   P/var/www/dbchiro/venv/lib/python3.4/site-packages/django_tables2/columns/base.py__init__   s    zLibrary.__init__c             C   s   |  j  j |  | S)N)r   append)r   columnr   r   r   register   s    zLibrary.registerc             C   so   | d k r |  j  d   SxN t |  j   D]= } t | d  sE q* n  | j |  } | d k rf q* n  | SWd S)z{
        Return a column object suitable for model field.

        Returns:
            `.Column` object or `None`
        Nr   
from_field)r   reversedhasattrr   )r   field	candidater   r   r   r   column_for_field   s    zLibrary.column_for_fieldN)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r      s   r   c               @   s   e  Z d  Z d Z d Z d Z d Z d d d d d d d d d d d d d  Z e d	 d
    Z	 e d d    Z
 d d   Z d d   Z d d   Z d d   Z e d d    Z d S)Columna	  
    Represents a single column of a table.

    `.Column` objects control the way a column (including the cells that fall
    within it) are rendered.

    Arguments:
        attrs (dict): HTML attributes for elements that make up the column.
            This API is extended by subclasses to allow arbitrary HTML
            attributes to be added to the output.

            By default `.Column` supports:

             - *th* -- ``table/thead/tr/th`` elements
             - *td* -- ``table/tbody/tr/td`` elements
             - *cell* -- fallback if *th* or *td* isn't defined
        accessor (str or `~.Accessor`): An accessor that describes how to
            extract values for this column from the :term:`table data`.
        default (str or callable): The default value for the column. This can be
            a value or a callable object [1]_. If an object in the data provides
            `None` for a column, the default will be used instead.

            The default value may affect ordering, depending on the type of data
            the table is using. The only case where ordering is not affected is
            when a `.QuerySet` is used as the table data (since sorting is
            performed by the database).
        empty_values (iterable): list of values considered as a missing value,
            for which the column will render the default value. Defaults to
            `(None, '')`
        exclude_from_export (bool): If `True`, this column will not be added to
            the data iterator returned from as_values().
        footer (str, callable): Defines the footer of this column. If a callable
            is passed, it can take optional keyword argumetns `column`,
            `bound_column` and `table`.
        order_by (str, tuple or `.Accessor`): Allows one or more accessors to be
            used for ordering rather than *accessor*.
        orderable (bool): If `False`, this column will not be allowed to
            influence row ordering/sorting.
        verbose_name (str): A human readable version of the column name.
        visible (bool): If `True`, this column will be rendered.
        localize: If the cells in this column will be localized by the
            `localize` filter:

              - If `True`, force localization
              - If `False`, values are not localized
              - If `None` (default), localization depends on the ``USE_L10N`` setting.


    .. [1] The provided callable object must not expect to receive any arguments.
    r   N FTc             C   s[  | d  k p' t  | t j  p' t |  sF t d t |  j   n  t |  rm | d  k	 rm t d   n  | r t |  n d  |  _ | |  _	 | |  _
 | |  _ | |  _ | p t |  d i   |  _ t  | t j  r | f n | } | d  k	 r t |  n d  |  _ | d  k	 r!| |  _ n  |	 |  _ t j |  _ t j d 7_ |
 |  _ | |  _ d  S)Nz-accessor must be a string or callable, not %sz:accessor must be string when default is used, not callableattrs   )
isinstancer   string_typescallable	TypeErrortyper   r	   accessor_defaultverbose_namevisible	orderablegetattrr$   r   order_byempty_valueslocalizer"   creation_counter_footerexclude_from_export)r   r-   r+   defaultr.   r/   r$   r1   r2   r3   footerr6   r   r   r   r   r   s*    				!!		zColumn.__init__c             C   s    t  |  j  r |  j   S|  j S)N)r(   r,   )r   r   r   r   r7      s    zColumn.defaultc             C   s   |  j  S)ae  
        The value used for the column heading (e.g. inside the ``<th>`` tag).

        By default this returns `~.Column.verbose_name`.

        :returns: `unicode` or `None`

        .. note::

            This property typically isn't accessed directly when a table is
            rendered. Instead, `.BoundColumn.header` is accessed which in turn
            accesses this property. This allows the header to fallback to the
            column name (it's only available on a `.BoundColumn` object hence
            accessing that first) when this property doesn't return something
            useful.
        )r-   )r   r   r   r   header   s    zColumn.headerc             C   sv   i |  d 6| d 6| d 6} |  j  d k	 rS t |  j   rI t |  j  |  S|  j  Sn  t |  d  rr t |  j |  Sd S)zB
        Returns the content of the footer, if specified.
        r   bound_columntableNrender_footerr#   )r5   r(   r   r   r<   )r   r:   r;   Zfooter_kwargsr   r   r   r8      s    

zColumn.footerc             C   s   | S)a  
        Returns the content for a specific cell.

        This method can be overridden by :ref:`table.render_FOO` methods on the
        table or by subclassing `.Column`.

        If the value for this cell is in `.empty_values`, this method is
        skipped and an appropriate default value is rendered instead.
        Subclasses should set `.empty_values` to ``()`` if they want to handle
        all values in `.render`.
        r   )r   valuer   r   r   render   s    zColumn.renderc             K   s   t  |  j |  } | S)a  
        Returns the content for a specific cell similarly to `.render` however
        without any html content. This can be used to get the data in the
        formatted as it is presented but in a form that could be added to a csv
        file.

        The default implementation just calls the `render` function but any
        subclasses where `render` returns html content should override this
        method.

        See `LinkColumn` for an example.
        )r   r>   )r   kwargsr=   r   r   r   r=      s    zColumn.valuec             C   s
   | d f S)a-  
        Returns the queryset of the table.

        This method can be overridden by :ref:`table.order_FOO` methods on the
        table or by subclassing `.Column`; but only overrides if second element
        in return tuple is True.

        returns:
            Tuple (queryset, boolean)
        Fr   )r   Zquerysetis_descendingr   r   r   order   s    zColumn.orderc             C   sY   |  t  k rU t | d  r- | j   j } n t | d | j  } |  d t |   Sd S)a
  
        Return a specialised column for the model field or `None`.

        Arguments:
            field (Model Field instance): the field that needs a suitable column
        Returns:
            `.Column` object or `None`

        If the column isn't specialised for the given model field, it should
        return `None`. This gives other columns the opportunity to do better.

        If the column is specialised, it should return an instance of itself
        that's configured appropriately for the field.
        get_related_fieldr-   N)r"   r   rB   r-   r0   namer   )clsr   r-   r   r   r   r      s
    zColumn.from_field)Nr#   )r   r   r    r!   r4   r2   Z	_explicitr   propertyr7   r9   r8   r>   r=   rA   classmethodr   r   r   r   r   r"   6   s   3		r"   c               @   s6  e  Z d  Z d Z d d   Z d d   Z e d d    Z e d d	    Z d
 d   Z	 d d   Z
 d d   Z e d d    Z e d d    Z e d d    Z d d   Z e d d    Z e d d    Z e d d    Z e d d    Z e d  d!    Z e d" d#    Z e d$ d%    Z d& S)'BoundColumna  
    A *run-time* version of `.Column`. The difference between
    `.BoundColumn` and `.Column`, is that `.BoundColumn` objects include the
    relationship between a `.Column` and a `.Table`. In practice, this
    means that a `.BoundColumn` knows the *"variable name"* given to the
    `.Column` when it was declared on the `.Table`.

    arguments:
        table (`~.Table`): The table in which this column exists
        column (`~.Column`): The type of column
        name (str): The variable name of the column used when defining the
                    `.Table`. In this example the name is ``age``::

                          class SimpleTable(tables.Table):
                              age = tables.Column()

    c             C   s(   | |  _  | |  _ | |  _ d  |  _ d  S)N)_tabler   rC   current_value)r   r;   r   rC   r   r   r   r     s    			zBoundColumn.__init__c             C   s   t  j |  j  S)N)r   Z	text_typer9   )r   r   r   r   __str__   s    zBoundColumn.__str__c             C   s   |  j  j p t |  j  S)zh
        Returns the string used to access data for this column out of the data
        source.
        )r   r+   r	   rC   )r   r   r   r   r+   #  s    zBoundColumn.accessorc             C   s  i |  j  d 6|  d 6} t |  d d  r_ t |  d d  r_ | j i |  j d 6|  j d 6 n  t |  j  j  } | j t |  j j   | j d i   } t	 | j d	 |  d
 | | d	 <t	 | j d |  d
 | | d <t	 | j d |  d
 | | d <t
 | d	  | d	 <t
 | d  | d <t
 | d  | d <|  j | d	  | d	 d <|  j | d  | d d <|  j | d  | d d <| S)a  
        Proxy to `.Column.attrs` but injects some values of our own.

        A ``th``, ``td`` and ``tf`` are guaranteed to be defined (irrespective
        of what's actually defined in the column attrs. This makes writing
        templates easier. ``tf`` is not actually a HTML tag, but this key name
        will be used for attributes for column's footer, if the column has one.
        r;   r:   current_recordFrI   recordr=   Zcellthr?   tdtfclass)rH   r0   updaterK   rI   dictr$   r   getr   r
   get_th_classget_td_class)r   r?   r$   Z
cell_attrsr   r   r   r$   +  s(    

$	
"""zBoundColumn.attrsc             C   sV   | j  d d  } | d k r' t   n d d   | j d  D } |  j j | |   S)z
        return a set of the classes from the class key in ``attrs``, augmented
        with the column name (or anything else added by Table.get_column_class_names()).
        rP   Nc             S   s   h  |  ] } | r |  q Sr   r   ).0cr   r   r   	<setcomp>b  s   	 z.BoundColumn._get_cell_class.<locals>.<setcomp> )rS   setsplitrH   Zget_column_class_names)r   r$   classesr   r   r   _get_cell_class\  s    1zBoundColumn._get_cell_classc             C   s   d j  t |  j |    S)zQ
        Returns the HTML class attribute for a data cell in this column
        rY   )joinsortedr]   )r   Ztd_attrsr   r   r   rU   f  s    zBoundColumn.get_td_classc             C   s   |  j  |  } | j d i   } |  j rF | j | j d d   n  |  j r | j |  j j rs | j d d  n | j d d   n  d j t |   S)zS
        Returns the HTML class attribute for a header cell in this column
        Z	_orderingr/   Z
descendingdescZ	ascendingZascrY   )	r]   rS   r/   add
is_orderedorder_by_aliasr@   r^   r_   )r   Zth_attrsr\   Zordering_classr   r   r   rT   l  s    		zBoundColumn.get_th_classc             C   s+   |  j  j } | d k r' |  j j } n  | S)z<
        Returns the default value for this column.
        N)r   r7   rH   )r   r=   r   r   r   r7   }  s    zBoundColumn.defaultc             C   s   |  j  j } | r | S|  j S)zS
        The value that should be used in the header cell for this column.
        )r   r9   r-   )r   Zcolumn_headerr   r   r   r9     s    zBoundColumn.headerc             C   s$   t  |  j j i |  d 6|  j d 6 S)Nr:   r;   )r   r   r8   rH   )r   r   r   r   r8     s    zBoundColumn.footerc             C   s"   |  j  j d  k	 p! t |  j  d  S)Nr<   )r   r5   r   )r   r   r   r   
has_footer  s    zBoundColumn.has_footerc             C   sJ   |  j  j d k	 r! |  j  j } n t |  j f  } |  j j rF | j S| S)z
        Returns an `.OrderByTuple` of appropriately prefixed data source
        keys used to sort this column.

        See `.order_by_alias` for details.
        N)r   r1   r   r+   rc   r@   opposite)r   r1   r   r   r   r1     s    zBoundColumn.order_byc             C   sI   t  |  j j p i  j |  j |  j   } |  j r< | j n | | _ | S)a  
        Returns an `OrderBy` describing the current state of ordering for this
        column.

        The following attempts to explain the difference between `order_by`
        and `.order_by_alias`.

        `.order_by_alias` returns and `.OrderBy` instance that's based on
        the *name* of the column, rather than the keys used to order the table
        data. Understanding the difference is essential.

        Having an alias *and* a keys version is necessary because an N-tuple
        (of data source keys) can be used by the column to order the data, and
        it's ambiguous when mapping from N-tuple to column (since multiple
        columns could use the same N-tuple).

        The solution is to use order by *aliases* (which are really just
        prefixed column names) that describe the ordering *state* of the
        column, rather than the specific keys in the data source should be
        ordered.

        e.g.::

            >>> class SimpleTable(tables.Table):
            ...     name = tables.Column(order_by=('firstname', 'last_name'))
            ...
            >>> table = SimpleTable([], order_by=('-name', ))
            >>> table.columns['name'].order_by_alias
            '-name'
            >>> table.columns['name'].order_by
            ('-first_name', '-last_name')

        The `OrderBy` returned has been patched to include an extra attribute
        ``next``, which returns a version of the alias that would be
        transitioned to if the user toggles sorting on this column, e.g.::

            not sorted -> ascending
            ascending  -> descending
            descending -> ascending

        This is useful otherwise in templates you'd need something like::

            {% if column.is_ordered %}
            {% querystring table.prefixed_order_by_field=column.order_by_alias.opposite %}
            {% else %}
            {% querystring table.prefixed_order_by_field=column.order_by_alias %}
            {% endif %}

        )r   rH   r1   rS   rC   rb   re   next)r   r1   r   r   r   rc     s    3*zBoundColumn.order_by_aliasc             C   s   |  j  |  j j p f  k S)N)rC   rH   r1   )r   r   r   r   rb     s    zBoundColumn.is_orderedc             C   s&   |  j  j d k	 r |  j  j S|  j j S)zU
        Return a `bool` depending on whether this column supports ordering.
        N)r   r/   rH   )r   r   r   r   r/     s    
zBoundColumn.orderablec             C   s   |  j  j d k	 r |  j  j S|  j j d d  } |  j j j   } | r t |  j  j	 |  } | r t
 | d  r | j j } q t | d | j  } n  t | t  r | Sn  t |  S)a  
        Return the verbose name for this column.

        In order of preference, this will return:
          1) The column's explicitly defined `verbose_name`
          2) The titlised model's `verbose_name` (if applicable)
          3) Fallback to the titlised column name.

        Any `verbose_name` that was not passed explicitly in the column
        definition is returned titlised in keeping with the Django convention
        of `verbose_name` being defined in lowercase and uppercased/titlised
        as needed by the application.

        If the table is using queryset data, then use the corresponding model
        field's `~.db.Field.verbose_name`. If it's traversing a relationship,
        then get the last field in the accessor (i.e. stop when the
        relationship turns from ORM relationships to object attributes [e.g.
        person.upper should stop at person]).
        N_rY   r   r-   )r   r-   rC   replacerH   dataZ	get_modelr	   r+   	get_fieldr   r   r0   r&   r   r   )r   rC   Zmodelr   r   r   r   r-     s    
zBoundColumn.verbose_namec             C   s
   |  j  j S)zO
        Returns a `bool` depending on whether this column is visible.
        )r   r.   )r   r   r   r   r.     s    zBoundColumn.visiblec             C   s
   |  j  j S)zW
        Returns `True`, `False` or `None` as described in ``Column.localize``
        )r   r3   )r   r   r   r   r3   $  s    zBoundColumn.localizeN)r   r   r    r!   r   rJ   rE   r+   r$   r]   rU   rT   r7   r9   r8   rd   r1   rc   rb   r/   r-   r.   r3   r   r   r   r   rG     s&   1

7	-rG   c               @   s   e  Z d  Z d Z d d   Z d d   Z d d   Z d d	   Z d
 d   Z d d   Z	 d d   Z
 d d   Z d d   Z d d   Z d d   Z d d   Z d d   Z d d   Z d d   Z d  d!   Z d" d#   Z d$ S)%BoundColumnsa  
    Container for spawning `.BoundColumn` objects.

    This is bound to a table and provides its `.Table.columns` property.
    It provides access to those columns in different ways (iterator,
    item-based, filtered and unfiltered etc), stuff that would not be possible
    with a simple iterator in the table class.

    A `BoundColumns` object is a container for holding `BoundColumn` objects.
    It provides methods that make accessing columns easier than if they were
    stored in a `list` or `dict`. `Columns` has a similar API to a `dict` (it
    actually uses a `~collections.OrderedDict` interally).

    At the moment you'll only come across this class when you access a
    `.Table.columns` property.

    Arguments:
        table (`.Table`): the table containing the columns
    c             C   s   | |  _  t   |  _ x t j |  D] \ } } t | | |  |  j | <} t | d | | j  | _ t | d | t | d | | j   | _ t | d | | j	  | _	 q% Wd  S)NZrender_Zvalue_Zorder_)
rH   r   r   r   	iteritemsrG   r0   r>   r=   rA   )r   r;   Zbase_columnsrC   r   Zbcr   r   r   r   @  s    	,zBoundColumns.__init__c             C   s   d d   |  j    D S)Nc             s   s   |  ] \ } } | Vq d  S)Nr   )rV   rC   r   r   r   r   	<genexpr>K  s    z)BoundColumns.iternames.<locals>.<genexpr>)rl   )r   r   r   r   	iternamesJ  s    zBoundColumns.iternamesc             C   s   t  |  j    S)N)listrn   )r   r   r   r   namesM  s    zBoundColumns.namesc             C   s   d d   |  j    D S)z}
        Return an iterator that exposes all `.BoundColumn` objects,
        regardless of visiblity or sortability.
        c             s   s   |  ] \ } } | Vq d  S)Nr   )rV   rC   r   r   r   r   rm   U  s    z'BoundColumns.iterall.<locals>.<genexpr>)rl   )r   r   r   r   iterallP  s    zBoundColumns.iterallc             C   s   t  |  j    S)N)ro   rq   )r   r   r   r   allW  s    zBoundColumns.allc             c   sB   x; |  j  j D]- } | |  j  j k r | |  j | f Vq q Wd S)aU  
        Return an iterator of ``(name, column)`` pairs (where ``column`` is a
        `BoundColumn`).

        This method is the mechanism for retrieving columns that takes into
        consideration all of the ordering and filtering modifiers that a table
        supports (e.g. `~Table.Meta.exclude` and `~Table.Meta.sequence`).
        N)rH   sequenceexcluder   )r   rC   r   r   r   rl   Z  s    
zBoundColumns.iteritemsc             C   s   t  |  j    S)N)ro   rl   )r   r   r   r   itemsh  s    zBoundColumns.itemsc             C   s   d d   |  j    D S)a_  
        Same as `BoundColumns.all` but only returns orderable columns.

        This is useful in templates, where iterating over the full
        set and checking ``{% if column.ordarable %}`` can be problematic in
        conjunction with e.g. ``{{ forloop.last }}`` (the last column might not
        be the actual last that is rendered).
        c             s   s   |  ] } | j  r | Vq d  S)N)r/   )rV   xr   r   r   rm   t  s    z-BoundColumns.iterorderable.<locals>.<genexpr>)rq   )r   r   r   r   iterorderablek  s    	zBoundColumns.iterorderablec             C   s   t  |  j    S)N)ro   rw   )r   r   r   r   r/   v  s    zBoundColumns.orderablec             C   s   d d   |  j    D S)z
        Same as `.iterorderable` but only returns visible `.BoundColumn`
        objects.

        This is geared towards table rendering.
        c             s   s   |  ] } | j  r | Vq d  S)N)r.   )rV   rv   r   r   r   rm     s    z+BoundColumns.itervisible.<locals>.<genexpr>)rq   )r   r   r   r   itervisibley  s    zBoundColumns.itervisiblec             C   s   t  |  j    S)N)ro   rx   )r   r   r   r   r.     s    zBoundColumns.visiblec             C   s   d |  j  | j _ d S)z^
        Hide a column.

        Arguments:
            name(str): name of the column
        FN)r   r   r.   )r   rC   r   r   r   hide  s    zBoundColumns.hidec             C   s   d |  j  | j _ d S)zo
        Show a column otherwise hidden.

        Arguments:
            name(str): name of the column
        TN)r   r   r.   )r   rC   r   r   r   show  s    zBoundColumns.showc             C   s
   |  j    S)z;
        Convenience API, alias of `.itervisible`.
        )rx   )r   r   r   r   __iter__  s    zBoundColumns.__iter__c             C   s6   t  | t j  r" | |  j   k S| |  j   k Sd S)z
        Check if a column is contained within a `BoundColumns` object.

        *item* can either be a `~.BoundColumn` object, or the name of a column.
        N)r&   r   r'   rn   rq   )r   itemr   r   r   __contains__  s    zBoundColumns.__contains__c             C   s   t  |  j    S)z^
        Return how many `~.BoundColumn` objects are contained (and
        visible).
        )lenr.   )r   r   r   r   __len__  s    zBoundColumns.__len__c             C   s   t  | t  rQ y$ t t |  j   | | d   SWq t k
 rM t  Yq Xnt t  | t j  r x' |  j   D] } | j	 | k rp | Sqp Wt
 d | |  j   f   n t d t |  j   d S)a!  
        Retrieve a specific `~.BoundColumn` object.

        *index* can either be 0-indexed or the name of a column

        .. code-block:: python

            columns['speed']  # returns a bound column with name 'speed'
            columns[0]        # returns the first column
        r%   z5Column with name '%s' does not exist; choices are: %sz.Column indices must be integers or str, not %sN)r&   intrf   r   rq   StopIteration
IndexErrorr   r'   rC   KeyErrorrp   r)   r*   r   )r   indexr   r   r   r   __getitem__  s    $zBoundColumns.__getitem__N)r   r   r    r!   r   rn   rp   rq   rr   rl   ru   rw   r/   rx   r.   ry   rz   r{   r}   r   r   r   r   r   r   rk   ,  s$   
			rk   N)
__future__r   r   collectionsr   	itertoolsr   Zdjango.utilsr   Zdjango.utils.safestringr   Z*django_tables2.templatetags.django_tables2r   Zdjango_tables2.utilsr	   r
   r   r   r   r   objectr   Zlibraryr   r"   Zpython_2_unicode_compatiblerG   rk   r   r   r   r   <module>   s   .%	 &