我想使用Columns of the API Reference中的linkify将链接添加到我的列表视图。我正在将Django 2与Django_tables2 v 2.0.0b3一起使用
我有一个带有两个上下文变量name
的URL,该变量从ListView和子字段species
传递:
URL.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'),
]
如果我手动键入URL,则可以访问DetailView。
我想使用该选项,在其中可以输入带有(视图名,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 %}
的链接?目前在文档中没有示例可以做到这一点。
答案 0 :(得分:3)
尝试从连续的角度进行思考。在每一行中,表都需要该行的种类。 django-tables2中使用的机制是访问器。它使您能够将所需的值告诉django-tables2。您不能使用变量(例如name
和species
,因为您希望从每个记录中检索它们。
因此,使用访问器(通常用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
上的文档是正确的,他们当然需要改进。