简体   繁体   English

Django/django-tables2 html 表格行点击编辑表格

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

sorry this post may be messy not sure how do explain what I am looking for very well but here goes nothing.抱歉,这篇文章可能很乱,不知道如何很好地解释我正在寻找的内容,但这里什么也没有。

I have a Django App and using django-table2 to print a data model to a table, the next thing I am looking to do it when the user clicks on the table row to redirect the page to a equivalent edit form我有一个 Django 应用程序并使用 django-table2 将数据模型打印到表中,接下来我要做的是当用户单击表行以将页面重定向到等效的编辑表单时

urls.py网址.py

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

tables.py表.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视图.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')

template模板

{% 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 %}

I am struggling to get the account code from the onclick even to pass the account code back to Django to move to the next page to begin editing the record我正在努力从 onclick 获取帐户代码,甚至将帐户代码传递回 Django 以移至下一页以开始编辑记录

I really think I am barking up the wrong tree with this我真的认为我在用这个叫错了树

any help would be very much appreciated任何帮助将不胜感激

I couldn't find any solution that suits my needs.我找不到任何适合我需求的解决方案。

All the solutions I found requires some weird processing in Javascript and parsing slugs and PK's from the table to redirect to the correct URL.我找到的所有解决方案都需要在 Javascript 中进行一些奇怪的处理,并解析表中的 slug 和 PK 以重定向到正确的 URL。

My solution?我的解决方案?

Define an absolute URL in your models.py在你的 models.py 中定义一个绝对 URL

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

Then in your tables.py, we add a data-href attribute to each column that we want to be clickable.然后在您的tables.py 中,我们向我们希望可点击的每一列添加一个data-href 属性。 This allows us to restrict which columns become clickable.这允许我们限制哪些列可点击。

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)

And in your template just add this simple event listener,在你的模板中添加这个简单的事件监听器,

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

Alternatively, if you just want the whole row to be clickable, just use Row attributes as defined in the docs,或者,如果您只希望整行可点击,只需使用文档中定义的 Row 属性,

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

and then change your template script too然后也更改您的模板脚本

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

I think i may have found a implementation for the above.我想我可能已经找到了上述的实现。

Putting a click event for a dialogue box with Django Tables2 使用 Django Tables2 为对话框设置点击事件

it is for deleting a row but the concept is the same它用于删除一行,但概念是相同的

I will test and check我会测试和检查

Ok after spending this evening on this, I have found a way to perform this action without adding the href tag into the python code,好的,在今晚花了这个晚上之后,我找到了一种无需在 python 代码中添加 href 标签即可执行此操作的方法,

by using Ajax I can get the account code from the table and then pass this through to the url通过使用 Ajax,我可以从表中获取帐户代码,然后将其传递给 url

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

adding the primary key to the url.py将主键添加到 url.py

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

and adding the customer_edit def to the views.py并将 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)

this is the most optimum way I could find to redirect to another view from Django without having the url specified inside of the python file, I am 100% that there is better ways to do this but for now this will be the accepted answer这是我能找到的从 Django 重定向到另一个视图的最佳方式,而无需在 python 文件中指定 url,我 100% 有更好的方法来做到这一点,但现在这将是公认的答案

I may be a little confused about what you are trying to do.我可能对你正在尝试做的事情有点困惑。 It seems like you are for some reason trying to have the view render a new response back from the click events on the table.似乎您出于某种原因试图让视图从表上的单击事件返回一个新的响应。 That is why you are getting tripped up with all this JavaScript rendering.这就是为什么您会被所有这些 JavaScript 渲染绊倒的原因。 You should simply have those cells render as links that go to where you need them to.您应该简单地将这些单元格呈现为指向您需要它们的位置的链接。

Take a look at the django-tables2 documentation for TemplateColumn.查看 TemplateColumn 的 django-tables2 文档。 You will want to just have it point to a template that creates the url given the record pk.您将只想让它指向一个模板,该模板创建给定记录 pk 的 url。

https://django-tables2.readthedocs.io/en/latest/pages/api-reference.html?highlight=templatecolumn#templatecolumn 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM