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

问题描述 投票:2回答:1

我想在Columns of the API Reference中使用linkify为我的listview添加一个链接。我正在使用Django 2和Django_tables2 v 2.0.0b3

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

URL.朋友

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'),
]

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

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

对于tables.py,我试过:

class SpeciesTable(tables.Table):
    species =tables.Column(linkify=('main:species', {'name': name,'slug':species}))

这给了NameError: name 'species' is not defined

species =tables.Column(linkify=('main:species', {'name': kwargs['name'],'slug':kwargs['species']}))

这给了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'}))

这些尝试给了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})

我如何添加类似于{% url "main:species" name=name species =object.species %}的链接?目前,文档中没有例子可以做到这一点。

django django-tables2
1个回答
3
投票

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

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

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

Accessors的概念可以在多个位置使用,也可以更改要在列中呈现的值。

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

你对linkify的文档是正确的,他们当然需要改进。

© www.soinside.com 2019 - 2024. All rights reserved.