在 Django_tables2 列上使用 linkify 选项来创建链接

ccs*_*csv 4 django django-tables2

我想使用API Reference 的 Columns中的 linkify 添加到列表视图的链接。我正在使用 Django 2 和 Django_tables2 v 2.0.0b3

我有一个带有两个上下文变量的 URL name,它们是从 ListView 和 slug 字段传递的species

网址.py

app_name = 'main'

urlpatterns = [
#The list view
path('genus/<slug:name>/species/', views.SpeciesListView.as_view(), name='species_list'),
# The Detail view
path('genus/<name>/species/<slug:species>', views.SpeciesDetailView.as_view(), name='species'),
]
Run Code Online (Sandbox Code Playgroud)

如果我手动输入 URL,则当前可以访问 DetailView。

我想使用可以输入元组(viewname,args/kwargs)的选项。

对于tables.py我尝试过:

class SpeciesTable(tables.Table):
    species =tables.Column(linkify=('main:species', {'name': name,'slug':species}))
Run Code Online (Sandbox Code Playgroud)

这给了一个NameError: name 'species' is not defined.

species =tables.Column(linkify=('main:species', {'name': kwargs['name'],'slug':kwargs['species']}))
Run Code Online (Sandbox Code Playgroud)

这给了一个NameError: name 'kwargs' is not defined.

我还尝试将以下变量更改为字符串:

species =tables.Column(linkify=('main:species', {'name': 'name','slug':'species'}))
species =tables.Column(linkify=('main:species', {'name': 'name','slug':'object.species'}))
Run Code Online (Sandbox Code Playgroud)

这些尝试给出了NoReverseMatch Reverse for 'species' with keyword arguments '{'name': 'name', 'slug': 'species'}' not found. 1 pattern(s) tried: ['genus\\/(?P<name>[^/]+)\\/species\\/(?P<species>[-a-zA-Z0-9_]+)$']

将其格式化为以下任何一种都会给出SyntaxError

species =tables.Column(kwargs={'main:species','name': name,'slug':species})
species =tables.Column(args={'main:species','name': name,'slug':species})
species =tables.Column(kwargs:{'main:species','name': name,'slug':species})
species =tables.Column(args:{'main:species','name': name,'slug':species})
Run Code Online (Sandbox Code Playgroud)

我如何添加类似的链接{% url "main:species" name=name species =object.species %}?目前文档中没有示例可以执行此操作。

Jie*_*ter 7

尝试从行的角度思考。在每一行中,表都需要该行的物种。django-tables2 中使用的机制是访问器。它使您能够告诉 django-tables2 您希望它用于某个值的值。您不能使用变量(例如namespecies),因为您希望从每个记录中检索它们。

因此,使用访问器(通常缩写为A),您的第一个示例如下所示:

class SpeciesTable(tables.Table):
    species = tables.Column(linkify=('main:species', {'name': tables.A('name'),'slug': tables.A('species')}))
Run Code Online (Sandbox Code Playgroud)

访问器的概念可用于多个地方,也可用于更改要在列中呈现的值。

不过,我建议get_absolute_url在您的模型上定义方法。这很好,因为通常当你想显示模型的链接时,你有一个它的实例,所以在模板中,这是一个问题{{ species.get_absolute_url }},对于linkifydjango-tables2 列的参数,你大多可以摆脱linkify=True

您对 上的文档的看法是正确的linkify,它们确实需要改进。

  • 我在“linkify”的文档中添加了一些示例:https://github.com/jieter/django-tables2/commit/204a7f23860d178afc8f3aef50512e6bf96f8f6b (3认同)