Skip to content

Commit

Permalink
More typing, remove RelatedLinkColumn
Browse files Browse the repository at this point in the history
  • Loading branch information
jieter committed Nov 6, 2024
1 parent a305902 commit 012f68e
Show file tree
Hide file tree
Showing 12 changed files with 23 additions and 92 deletions.
2 changes: 0 additions & 2 deletions django_tables2/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
JSONColumn,
LinkColumn,
ManyToManyColumn,
RelatedLinkColumn,
TemplateColumn,
TimeColumn,
URLColumn,
Expand All @@ -35,7 +34,6 @@
"JSONColumn",
"LinkColumn",
"ManyToManyColumn",
"RelatedLinkColumn",
"TemplateColumn",
"TimeColumn",
"URLColumn",
Expand Down
3 changes: 1 addition & 2 deletions django_tables2/columns/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from .emailcolumn import EmailColumn
from .filecolumn import FileColumn
from .jsoncolumn import JSONColumn
from .linkcolumn import LinkColumn, RelatedLinkColumn
from .linkcolumn import LinkColumn
from .manytomanycolumn import ManyToManyColumn
from .templatecolumn import TemplateColumn
from .timecolumn import TimeColumn
Expand All @@ -26,7 +26,6 @@
"JSONColumn",
"LinkColumn",
"ManyToManyColumn",
"RelatedLinkColumn",
"TemplateColumn",
"URLColumn",
"TimeColumn",
Expand Down
4 changes: 3 additions & 1 deletion django_tables2/columns/datetimecolumn.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Self

from django.db import models

from .base import library
Expand All @@ -23,6 +25,6 @@ def __init__(self, format=None, short=True, *args, **kwargs):
super().__init__(template_code=template, *args, **kwargs)

@classmethod
def from_field(cls, field, **kwargs):
def from_field(cls, field, **kwargs) -> Self | None:
if isinstance(field, models.DateTimeField):
return cls(**kwargs)
6 changes: 4 additions & 2 deletions django_tables2/columns/emailcolumn.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from typing import Self

from django.db import models

from .base import library
Expand Down Expand Up @@ -31,10 +33,10 @@ class PeopleTable(tables.Table):
# [...]<a href="mailto:[email protected]">[email protected]</a>
"""

def get_url(self, value):
def get_url(self, value) -> str:
return f"mailto:{value}"

@classmethod
def from_field(cls, field, **kwargs):
def from_field(cls, field, **kwargs) -> Self | None:
if isinstance(field, models.EmailField):
return cls(**kwargs)
6 changes: 4 additions & 2 deletions django_tables2/columns/filecolumn.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import os
from typing import Self

from django.db import models
from django.utils.html import format_html
from django.utils.safestring import SafeString

from ..utils import AttributeDict
from .base import library
Expand Down Expand Up @@ -50,7 +52,7 @@ def text_value(self, record, value):
return os.path.basename(value.name)
return super().text_value(record, value)

def render(self, record, value):
def render(self, record, value) -> SafeString:
attrs = AttributeDict(self.attrs.get("span", {}))
classes = [c for c in attrs.get("class", "").split(" ") if c]

Expand Down Expand Up @@ -80,6 +82,6 @@ def render(self, record, value):
)

@classmethod
def from_field(cls, field, **kwargs):
def from_field(cls, field, **kwargs) -> Self | None:
if isinstance(field, models.FileField):
return cls(**kwargs)
24 changes: 8 additions & 16 deletions django_tables2/columns/jsoncolumn.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
import json
from typing import Self

from django.db.models import JSONField
from django.utils.html import format_html
from django.utils.safestring import SafeString

from ..utils import AttributeDict
from .base import library
from .linkcolumn import BaseLinkColumn

try:
from django.contrib.postgres.fields import HStoreField

POSTGRES_AVAILABLE = True
except ImportError:
# psycopg2 is not available, cannot import from django.contrib.postgres.
# JSONColumn might still be useful to add manually.
POSTGRES_AVAILABLE = False
# psycopg is not available, cannot import from django.contrib.postgres.
HStoreField = object()


@library.register
Expand All @@ -25,12 +24,6 @@ class JSONColumn(BaseLinkColumn):
.. versionadded :: 1.5.0
.. note::
Automatic rendering of data to this column requires PostgreSQL support
(psycopg2 installed) to import the fields, but this column can also be
used manually without it.
Arguments:
json_dumps_kwargs: kwargs passed to `json.dumps`, defaults to `{'indent': 2}`
attrs (dict): In addition to *attrs* keys supported by `~.Column`, the
Expand All @@ -47,15 +40,14 @@ def __init__(self, json_dumps_kwargs=None, **kwargs):

super().__init__(**kwargs)

def render(self, record, value):
def render(self, record, value) -> SafeString:
return format_html(
"<pre {}>{}</pre>",
AttributeDict(self.attrs.get("pre", {})).as_html(),
json.dumps(value, **self.json_dumps_kwargs),
)

@classmethod
def from_field(cls, field, **kwargs):
if POSTGRES_AVAILABLE:
if isinstance(field, (JSONField, HStoreField)):
return cls(**kwargs)
def from_field(cls, field, **kwargs) -> Self | None:
if isinstance(field, (JSONField, HStoreField)):
return cls(**kwargs)
34 changes: 0 additions & 34 deletions django_tables2/columns/linkcolumn.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,37 +143,3 @@ def __init__(
),
**extra
)


@library.register
class RelatedLinkColumn(LinkColumn):
"""
Render a link to a related object using related object's ``get_absolute_url``,
same parameters as ``~.LinkColumn``.
.. note ::
This column should not be used anymore, the `linkify` keyword argument to
regular columns can be used achieve the same results.
If the related object does not have a method called ``get_absolute_url``,
or if it is not callable, the link will be rendered as '#'.
Traversing relations is also supported, suppose a Person has a foreign key to
Country which in turn has a foreign key to Continent::
class PersonTable(tables.Table):
name = tables.Column()
country = tables.RelatedLinkColumn()
continent = tables.RelatedLinkColumn(accessor="country.continent")
will render:
- in column 'country', link to ``person.country.get_absolute_url()`` with the output of
``str(person.country)`` as ``<a>`` contents.
- in column 'continent', a link to ``person.country.continent.get_absolute_url()`` with
the output of ``str(person.country.continent)`` as ``<a>`` contents.
Alternative contents of ``<a>`` can be supplied using the ``text`` keyword argument as
documented for `~.columns.LinkColumn`.
"""
6 changes: 0 additions & 6 deletions docs/pages/api-reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -323,12 +323,6 @@ Columns
.. autoclass:: django_tables2.columns.ManyToManyColumn
:members:

`.RelatedLinkColumn`
~~~~~~~~~~~~~~~~~~~~

.. autoclass:: django_tables2.columns.RelatedLinkColumn
:members:


`.TemplateColumn`
~~~~~~~~~~~~~~~~~
Expand Down
1 change: 0 additions & 1 deletion docs/pages/builtin-columns.rst
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ For common use-cases the following columns are included:
- `.JSONColumn` -- renders JSON as an indented string in ``<pre></pre>``
- `.LinkColumn` -- renders ``<a href="...">`` tags (compose a Django URL)
- `.ManyToManyColumn` -- renders a list objects from a `ManyToManyField`
- `.RelatedLinkColumn` -- renders ``<a href="...">`` tags linking related objects
- `.TemplateColumn` -- renders template code
- `.TimeColumn` -- time formatting
- `.URLColumn` -- renders ``<a href="...">`` tags (absolute URL)
2 changes: 1 addition & 1 deletion example/app/tables.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ class Meta:


class SemanticTable(tables.Table):
country = tables.RelatedLinkColumn()
country = tables.Column(linkify=True)

class Meta:
model = Person
Expand Down
25 changes: 1 addition & 24 deletions tests/columns/test_linkcolumn.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import django_tables2 as tables
from django_tables2 import A

from ..app.models import Occupation, Person
from ..app.models import Person
from ..utils import attrs, build_request


Expand Down Expand Up @@ -200,29 +200,6 @@ class Table(tables.Table):
with self.assertRaisesMessage(TypeError, message):
table.as_html(build_request())

def test_RelatedLinkColumn(self):
carpenter = Occupation.objects.create(name="Carpenter")
Person.objects.create(first_name="Bob", last_name="Builder", occupation=carpenter)

class Table(tables.Table):
occupation = tables.RelatedLinkColumn()
occupation_linkify = tables.Column(accessor="occupation", linkify=True)

table = Table(Person.objects.all())

url = reverse("occupation", args=[carpenter.pk])
self.assertEqual(table.rows[0].cells["occupation"], f'<a href="{url}">Carpenter</a>')

def test_RelatedLinkColumn_without_model(self):
class Table(tables.Table):
occupation = tables.RelatedLinkColumn()

table = Table([{"occupation": "Fabricator"}])

message = "for linkify=True, 'Fabricator' must have a method get_absolute_url"
with self.assertRaisesMessage(TypeError, message):
table.rows[0].cells["occupation"]

def test_value_returns_a_raw_value_without_html(self):
class Table(tables.Table):
col = tables.LinkColumn("occupation", args=(A("id"),))
Expand Down
2 changes: 1 addition & 1 deletion tests/test_extra_columns.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ def __init__(self, data, *args, **kwargs):

if add_occupation_column:
kwargs["extra_columns"].append(
("occupation", tables.RelatedLinkColumn(orderable=False))
("occupation", tables.Column(linkify=True, orderable=False))
)

super().__init__(data, *args, **kwargs)
Expand Down

0 comments on commit 012f68e

Please sign in to comment.