Search code examples
pythondjangodjango-tables2

Django_tables2 with delete buttom


How is going? I'm learning to programming in django. For the moment I'm building a simple app that utilizing a form update the referenced table.

Now I'm try to add a delete button in each row of my table but, beside I have tried a lot of solutions, I didn't find one that works correctly.

Below my code:

urls


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"),
]

forms

from django import forms
from .models import Income

class IncomeModelForm(forms.ModelForm):

    class Meta:
        model = Income
        fields = "__all__"

tables

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"

views

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)

html

{% load static %}
{% load render_table from django_tables2 %}
<!doctype html>
<html lang="it">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <title>Hello, world!</title>
  </head>
  <div class="container">
        <form class="" action="" method="post">
            {% csrf_token %}
            {{form|crispy}}
            <input type="submit" class="btn btn-danger" value="INVIA">
        </form>
</div>

<br>
<br>

<div class="container">
    {% render_table table %}
</form>
</div>

  </body>
</html>

My table disply the column "Delete" but no buttoms, only a "-". Why? Where is my error?


Solution

  • Please add this

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

    Hope it will work