如何在表格的每一行中添加删除按钮?

进展如何?我正在学习用django编程。目前,我正在构建一个简单的应用程序,该应用程序利用表单更新引用的表。


现在,我尝试在表的每一行中添加一个删除按钮,但是,除了我尝试了很多解决方案之外,我没有找到一个正常工作的解决方案。


在我的代码下面:


网址



from django.urls import path

from app import views


app_name = 'main'


urlpatterns = [

    path('', views.homepage, name='homepage'),

    path('delete_item/<int:pk>', views.delete_item, name="delete_item"),

]


形式


from django import forms

from .models import Income


class IncomeModelForm(forms.ModelForm):


    class Meta:

        model = Income

        fields = "__all__"



import django_tables2 as tables

from django_tables2.utils import A

from .models import Income


class PersonTable(tables.Table):

    delete = tables.LinkColumn('main:delete_item', args=[A('delete-id')], attrs={'a': {'class': 'btn'}})

    class Meta:

        model = Income

        template_name = "django_tables2/bootstrap.html"


视图


from django.shortcuts import render

from django.http import HttpResponse

from django.views.generic import ListView

from .models import Income

from .tables import PersonTable

from .forms import IncomeModelForm


def homepage(request):

    table = PersonTable(Income.objects.all())


    if request.method == 'POST':

         form = IncomeModelForm(request.POST)

         if form.is_valid():

             print("Il form è valido")

             new_input = form.save()


    else :

        form = IncomeModelForm()


    context= {"form": form,

            "table":table }

    return render(request, "app/base.html", context)



def delete_item(request, pk):


    Income.objects.filter(id=pk).delete()

    items = Income.objects.all()

    context = {

    'items': items

    }

    return render(request, 'app/base.html', context)

断续器


{% load static %}

{% load render_table from django_tables2 %}

<!doctype html>

<html>

  <head>

    <!-- Required meta tags -->

    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">



我的表取消了“删除”列,但没有 buttoms,只有一个“-”。为什么?我的错误在哪里?


斯蒂芬大帝
浏览 140回答 1
1回答

青春有我

在表中显示记录时,需要使用“删除表单”按钮添加额外的表数据。例如:<table>{% for item in items%}<tr><td>{{item.id}}</td><td>{{item.name}}</td><td>&nbsp; &nbsp; <form method="delete">&nbsp; &nbsp; &nbsp; &nbsp; <input type="hidden" value="{{item.id}}" name="delete-id">&nbsp; &nbsp; &nbsp; &nbsp; <input type="Submit">Delete</button>&nbsp; &nbsp; </form></td></tr>{% endfor}</table>现在,在 views.py 添加删除部分并删除记录:if request.method == 'DELETE':&nbsp; &nbsp; &nbsp; &nbsp; Person.objects.get(pk=request.DELETE['delete-id']).delete()您正在使用django_tables2,您只需将此代码添加到 tables.pyfrom django_tables2.utils import A&nbsp; # alias for Accessorclass PersonTable(tables.Table):&nbsp; &nbsp; delete = tables.LinkColumn('main:delete_item', args=[A('delete-id')], attrs={&nbsp; &nbsp; 'a': {'class': 'btn'}&nbsp; &nbsp; })
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python