首页 > 解决方案 > Django - 如何按用户从模型中删除条目?

问题描述

我是 Django 框架的新手。我正在开发一个网络应用程序。在这个应用程序中,我有一个条目列表,例如(标题和描述)。我又添加了一个包含删除按钮的列。我希望当有人单击该按钮(删除按钮)时,它会删除条目。对于前端,我使用的是 Bootstrap。

我的views.py

from django.http import request
from .models import Task
from django.http.response import HttpResponse
from django.shortcuts import render

# Create your views here.
def home(request):
    context = {"success":  False}
    if request.method=='POST':
        title= request.POST['title']
        desc = request.POST['desc']
        print(title, desc)
        ins = Task(title=title, desc=desc)
        ins.save()
        context = {"success":  True}
    return render(request, 'index.html', context)

def tasks(request):
    alltasks = Task.objects.all()
    # print(alltasks)
    # for item in alltasks:
    #     print(item.title)
    context = {'tasks': alltasks}
       
    
    return render(request, 'tasks.html', context)

我的urls.py

from django.contrib import admin
from django.urls import path
from . import views

urlpatterns = [
    path('', views.home, name="home"),
    path('tasks', views.tasks, name="tasks"),
    
]

还有我的模板

<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

    <title>Tasks</title>
  </head>
  <body>
    
    <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
        <a class="navbar-brand" href="/">TODO</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
      
        <div class="collapse navbar-collapse" id="navbarSupportedContent">
          <ul class="navbar-nav mr-auto">
            <li class="nav-item ">
              <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a>
            </li>
            <li class="nav-item active">
              <a class="nav-link" href="/tasks">Tasks</a>
            </li>
        </div>
        <form class="form-inline my-2 my-lg-0">
            <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
            <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
          </form>
    </nav>
    <h2 class="text-center py-3"> <b>Here is your Tasks</b> </h2>
    <div class="container">
    <table class="table">
        <thead>
          <tr>
            <th scope="col">S.No.</th>
            <th scope="col">Date</th>
            <th scope="col">Task Title</th>
            <th scope="col">Task Description</th>
            <th scope="col">Action</th>
            
          </tr>
        </thead>
        <tbody>
        {% for task in tasks %}
          <tr>
            <th scope="row">{{forloop.counter}}</th>
            <td>{{task.time}}</td>
            <td>{{task.title}}</td>
            <td>{{task.desc}}</td>
            <td><button  type="button" class="btn btn-danger btn-sm">Delete</button></td>
          </tr>
        {% endfor %}
          
        </tbody>
      </table>
    </div>
    <footer>
      <p class="text-center bg-dark text-light fixed-bottom my-0 py-2">
        Copyright &copy; 2020 | All rights reserved

      </p>
    </footer>
    

    <!-- Optional JavaScript; choose one of the two! -->

    <!-- Option 1: jQuery and Bootstrap Bundle (includes Popper) -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ho+j7jyWK8fNQe+A12Hb8AhRq26LrZ/JpcUGGOn+Y7RsweNrtN/tE3MoK7ZeZDyx" crossorigin="anonymous"></script>

    <!-- Option 2: jQuery, Popper.js, and Bootstrap JS
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/js/bootstrap.min.js" integrity="sha384-w1Q4orYjBQndcko6MimVbzY0tgp4pWB4lZ7lr30WKz0vr/aWKhXdBNmNb5D92v7s" crossorigin="anonymous"></script>
    -->
  </body>
</html>

标签: pythondjangobootstrap-4django-views

解决方案


delete()不是delete。所以:

def delete_view():
    object = Task.objects.get(id = part_id)
    object.delete()
    return render(request, 'tasks.html')

参考文献

笔记

因为你的delete动作应该有点安全。所以最好使用POST方法而不是简单的GET方法。因此,在您的模板中添加POST方法,例如:

...
{% for task in tasks %}
      <tr>
        <th scope="row">{{forloop.counter}}</th>
        <td>{{task.time}}</td>
        <td>{{task.title}}</td>
        <td>{{task.desc}}</td>
        <td>
            <form action="url: delete_view"" method="post">
                {% csrf_token %}
                <button type="submit" value="Delete" class="btn btn-danger btn-sm">Delete</button>
            </form>
        </td>
      </tr>
{% endfor %}

并且您的 delete_view() 将仅在请求为时删除POST

def delete_view():
    if request.POST:
        object = Task.objects.get(id = part_id)
        object.delete()
    return render(request, 'tasks.html')

推荐阅读