Django/django-tables2 html table on row click to edit form



抱歉,这篇文章可能很混乱,不确定如何很好地解释我正在寻找的东西,但这里什么都没有。

我有一个 Django 应用程序并使用 django-table2 将数据模型打印到表中,当用户单击表格行将页面重定向到等效的编辑表单时,我要做的下一件事

是urls.py

path('', CustomerView.as_view(), name='customer'),
path('customer_edit/', views.customer_edit, name='customer_edit'),

tables.py

import django_tables2 as tables
from customer.models import Customer

class CustomerTable(tables.Table):
account = tables.Column(attrs={'td': {'class': 'account'}})
class Meta:
model = Customer
attrs = {'id': 'table'}
exclude = ('is_deleted',)
template_name = 'django_tables2/bootstrap-responsive.html'

views.py

from django.shortcuts import render
from django_tables2 import RequestConfig
from customer.models import Customer
from customer.tables import CustomerTable
from django.views.generic import TemplateView

class CustomerView(TemplateView):
template_name = 'customer/customer.html'
def get(self, request, *args, **kwargs):
table = CustomerTable(Customer.objects.all().filter(is_deleted=False))
RequestConfig(request).configure(table)
return render(request, 'customer/customer.html', {'table': table})
def customer_edit(request):
return render(request, 'customer/customer_edit.html')

模板

{% extends 'base.html' %}
{% load render_table from django_tables2 %}
{% block head %}
<title>Dev Genie - Customers</title>
{% endblock %}
{% block body %}
<div class="input-group col-md-6">
<input type="button" class="btn btn-success" value="Add">
<input type="button" class="btn btn-danger" value="Delete">
<input class="form-control py-2" type="search" value="search" id="example-search-input">
<span class="input-group-append">
<button class="btn btn-outline-secondary" type="button">
<span class="glyphicon glyphicon-search"></span>
</button>
</span>
</div>
{% render_table table %}
<script>
$(document).ready(function () {
$('table:first').children('tbody:first').children('tr:first').css('background-color', '#0099ff');
$('table tbody tr').bind("mouseover", function () {
var colour = $(this).css("background-color");
$(this).css("background", '#0099ff');
$(this).bind("mouseout", function () {
$(this).css("background", colour);
});
});
$('table tbody tr').click(function () {
let account = $(this).closest('tr').find('td.account').text();
alert(account);
//on table row click event, pass back to django
});
});
</script>
{% endblock %}

我正在努力从onclick获取帐户代码,甚至将帐户代码传递回Django以移动到下一页以开始编辑记录

我真的认为我用这个吠错了树

任何帮助将不胜感激

我找不到任何适合我需求的解决方案。

我找到的所有解决方案都需要在 Javascript 中进行一些奇怪的处理,并从表中解析 slug 和 PK 以重定向到正确的 URL。

我的解决方案?

在 models.py 中定义绝对网址

def get_absolute_url(self):
return reverse('product:detail', kwargs={'slug': self.slug})

然后在您的 tables.py 中,我们为要点击的每一列添加一个 data-href 属性。这使我们能够限制哪些列可点击。

class ProductTable(tables.Table):
clickable = {'td': {'data-href': lambda record: record.get_absolute_url}}
name = tables.Column(attrs=clickable)
in_stock = tables.Column(attrs=clickable)
class Meta:
model = Product
fields = (name, in_stock)

在您的模板中,只需添加这个简单的事件侦听器,

$(document).ready(function($) {
$("td").click(function() {
window.location = $(this).data("href");
});
});

或者,如果您只想单击整行,只需使用文档中定义的 Row 属性,

class ProductTable(tables.Table):
class Meta:
model = Product
row_attrs = {'data-href': lambda record: record.get_absolute_url}
fields = (name, in_stock)

然后也更改模板脚本

$(document).ready(function($) {
$("tr").click(function() {
window.location = $(this).data("href");
});
});

我想我可能已经找到了上述实现。

使用 Django 表为对话框放置一个点击事件2

它用于删除一行,但概念是相同的

我会测试和检查

在行单击或列时执行此操作的简单代码

row_attrs = {
"onClick": lambda record: "document.location.href='/app/view/{0}';".format(record.id)
}

如果要在 col 上使用它,请使用表。列 文档

好的,在今晚花了这个时间之后,我找到了一种方法来执行此操作,而无需将 href 标签添加到 python 代码中,

通过使用 Ajax,我可以从表中获取帐户代码,然后将其传递给 url

$('table tbody tr').click(function () {
let account = $(this).closest('tr').find('td.account').text();
window.location = account;
});

将主键添加到 url.py

path('<slug:account>/', views.customer_edit, name='customer_edit'),

并将customer_edit def 添加到 views.py

def customer_edit(request, account):
customer = get_object_or_404(Customer, pk=account)
if request.method == 'POST':
form = CustomerEdit(request.POST, instance=customer)
if form.is_valid():
customer.save()
return redirect(reverse('customer:customer'))
else:
form = CustomerEdit(instance=customer)
args = {'customer': customer, 'form': form}
return render(request, 'customer/customer_edit.html', args)

这是我能找到的从 Django 重定向到另一个视图而无需在 python 文件中指定 url 的最佳方法,我 100% 认为有更好的方法来做到这一点,但现在这将是公认的答案

我可能对你想做什么有点困惑。 似乎出于某种原因,您正在尝试让视图从表上的单击事件中呈现新的响应。 这就是为什么你会被所有这些JavaScript渲染绊倒的原因。您应该简单地将这些单元格呈现为指向您需要它们的位置的链接。

看看 TemplateColumn 的 django-tables2 文档。 您将希望仅将其指向创建给定记录 pk 的 url 的模板。

https://django-tables2.readthedocs.io/en/latest/pages/api-reference.html?highlight=templatecolumn#templatecolumn

tables.py
class CustomerTable(tables.Table):
account = tables.TemplateColumn(template_name="_account.html")
def render_title(self, record, value, column, bound_column, bound_row):
value = self.value_title(record, value)
return mark_safe(  # noqa: S308, S703
column.render(record, self, value, bound_column, bound_row=bound_row)
)

_account.html
<a href={% url('customer_edit', args=[record.pk]) %}>your text here</a>

最新更新