How to put submit buttons for every record in djan

2020-08-01 06:37发布

问题:

I have a django_tables2 table inside a form, this is necessary because there's a delete selected button on top. In every row, I need a submit button with some action like 'accept', 'deny', etc.

But I don't know how to recognize the row of which the button was pressed. How can I accomplish this?

回答1:

I have found this way to add a button to each row with an id that refers to the row you select :

in app/tables.py

import django_tables2 as tables
from app.models import MyModel
from django.utils.safestring import mark_safe
from django.utils.html import escape

class MyColumn(tables.Column): 
    empty_values = list() 
    def render(self, value, record): 
        return mark_safe('<button id="%s" class="btn btn-info">Submit</button>' % escape(record.id))

class MyTable(tables.Table):
    submit = MyColumn()
    class Meta:
        model = MyModel
        ...

in app/views.py, just like usual :

def mypage(request) :
    table = MyTable(MyModel.objects.all())
    RequestConfig(request,paginate=False).configure(table)
    return render(request,'template.html',locals())

Then I use Jquery to trigger what I want for each button by retrieving their id ...

Maybe it is a little bit too simple for what you want to do, I've seen other solutions maybe more efficient with LinkColumns and Django URL dispatcher : Django-Tables2 LinkColumn link doesn't work