简体   繁体   English

Django - 如何由用户从 model 中删除条目?

[英]Django - How to delete an entry from model by user?

I am new in Django framework.我是 Django 框架的新手。 And I am developing a web app.我正在开发一个 web 应用程序。 In this app I have a list of entries like (Title and description).在这个应用程序中,我有一个条目列表,例如(标题和描述)。 I have add one more column that contains a delete button.我又添加了一个包含删除按钮的列。 I want when someone click on that button (delete button) it deletes entry.我希望当有人单击该按钮(删除按钮)时,它会删除条目。 For front end I am using Bootstrap.对于前端,我使用的是 Bootstrap。

my views.py我的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)

my urls.py我的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"),
    
]

And my template还有我的模板

<!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>

It is delete() not delete .它是delete()而不是delete So:所以:

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

Refs 参考文献

Note笔记

Because your delete action should be somewhat secure.因为您的delete操作应该有点安全。 So it is better to use POST method instead of simple GET method.所以最好使用POST方法而不是简单的GET方法。 So add POST method in your template like:因此,在您的模板中添加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 %}

And your delete_view() will delete only if the request is POST :只有当请求是POST时,您的 delete_view() 才会删除:

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

You can use Django's generic class-based view您可以使用 Django 的通用基于类的视图

from django.views.generic.edit import DeleteView
from .models import Task
    
class DeleteTrackView(DeleteView):
    model = Task
    success_url = reverse_lazy(<task_list>)
    template_name = "<path_to_template>"

In template在模板中

<form method="post">{% csrf_token %}
    <p>Are you sure you want to delete "{{ object }}"?</p>
    <input type="submit" value="Confirm">
</form>

Using generic class-based views you can avoid redundant boilerplate codes.使用基于类的通用视图可以避免多余的样板代码。

Ref: https://docs.djangoproject.com/en/3.1/ref/class-based-views/generic-editing/#deleteview参考: https://docs.djangoproject.com/en/3.1/ref/class-based-views/generic-editing/#deleteview

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

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