1

我使用 django 和 MySQL 作为数据库来执行添加、编辑和删除详细信息。我使用下面的代码执行了添加和编辑,但删除不起作用。

视图.py:

import logging
import smtplib
from django.db import connection
from django.shortcuts import render
from django.http import HttpResponse
from polls.models import Poll
from django.template import Context, loader
from django.shortcuts import get_object_or_404, render_to_response
from myapp.models import Book
from django.shortcuts import render_to_response,redirect
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.core.context_processors import csrf
from django.template import RequestContext

log = logging.getLogger(__name__)

def index(request):

    books = Book.objects.all()
    context={'books':books}
    return render(request,'index.html', context)

def addbook(request):
    if request.POST:
        book_name =request.POST['book_name']
        author_name =request.POST['author_name']
    publisher_name =request.POST['publisher_name']
    book = Book(book_name=book_name, author_name=author_name, publisher_name=publisher_name)
        book.save()
        return render_to_response('book_detail.html', {'books': book},context_instance=RequestContext(request))
    else:
        return render_to_response('addbook.html',context_instance=RequestContext(request))

def book_detail(request):
    return render(request, 'book_detail.html') 

def editbook(request,book_id):
    if request.POST:
        book_name =request.POST['book_name']
        author_name =request.POST['author_name']
    publisher_name =request.POST['publisher_name']
    books=Book.objects.filter(book_id=book_id).update(book_name=book_name, author_name=author_name, publisher_name=publisher_name)
        return redirect('/index/')
    else:
        books = Book.objects.get(pk=book_id)
    return render_to_response('editbook.html',{'books':books},context_instance=RequestContext(request))

def deletebook(request,book_id):
    if request.POST:
        book_name =request.POST['book_name']
        author_name =request.POST['author_name']
    publisher_name =request.POST['publisher_name']
    books=Book.objects.filter(book_id=book_id).delete(book_name=book_name, author_name=author_name, publisher_name=publisher_name)
        return redirect('/index/')
    else:
        books = Book.objects.get(pk=book_id)
    return render_to_response('deletebook.html',{'books':books},context_instance=RequestContext(request))

网址.py:

from django.conf.urls import patterns, include, url
from DemoApp.views import index,addbook,editbook, book_detail
from django.contrib import admin

admin.autodiscover()

urlpatterns = patterns('',
    url('^$', index),
    url('^index/$', index),
    url('^addbook/$', addbook),
    url('^book_detail/$', book_detail, 'book_summary'),
    url('^editbook/(?P<book_id>\d+)/$',editbook) ,
    url('^deletebook/(?P<book_id>\d+)/$',deletebook) ,

    #url(r'^admin/', include(admin.site.urls)),

)

HTML 模板:

<html>
    <head>
        <title>{{ page_title }}</title>
    </head>
    <body>   
        <div align="center">
            <table border="0" cellpadding='5' cellspacing='5'>
                <tr>
                    <form action="/deletebook/{{ books.book_id}}/" method="POST"> {% csrf_token %}
                        <input type="text" name="book_name" value="{{books.book_name}}"></input><br>
                        <input type="text" name="author_name" value="{{books.author_name}}"></input><br>
                        <input type="text" name="publisher_name" value="{{books.publisher_name}}"></input><br>
                        <input type="submit" value="delete">
                    </form>
                    <p> Output: {{ output }} </p>
                    <p>{{ book_name }}</p>
                </tr>  
            </table>
        </div>
    </body>
</html>

我没有使用任何形式。我无法对特定行执行删除操作。它给出了一条错误消息。请检查此片段并用正确的片段回复我。

我的要求是我想从表中删除选定的行。我正在使用 MySQL。

4

4 回答 4

0

我不太了解 django,但清空表的 SQL 命令是:

TRUNCATE table table_name;

它会将自动增量重新设置为 1,如果您不想更改该使用:

Delete * from table_name;

如果你想删除特定的行然后

Delete from table_name where conditions1, condition2
于 2013-03-01T05:15:54.807 回答
0

首先尝试打印从查询中获得的值,以确定是否有任何内容符合您的delete条件:

books = Book.objects.filter(book_id=book_id, book_name=book_name, author_name=author_name, publisher_name=publisher_name)
print '\n'.join([str(b) for b in books])

你为什么要查询book_name,如果你已经author_name给出了?我想您想删除与给定 id 匹配的书籍(将来会非常感谢更多的散文)。查询将是:publisher_namebook_id

Book.objects.filter(book_id=book_id).delete()

另外,请确保book_id是 的现有属性Book默认情况下,Django 使用一个名为id,的主键book_id是您手动更改的。

于 2013-03-04T09:55:39.440 回答
0

{% for i in obj %}
 
 <a href="{% url 'product_delete' %}?id={{ i.id }}"><button type="submit" class="btn btn-primary">Delete</button></a>

{% endfor %}

product_delete 是我在views.py中写的函数

urls.py 文件:

urlpatterns = [
path('page', views.page, name='page')
path('product_delete', views.product_delete, name='product_delete')
]

视图.py 文件:

def page(request):
    return render(request, "page.html")

def product_delete(request):
    if request.GET.get('id'):
        i=request.GET['id']
        with connection.cursor() as cursor:
                        cursor.execute('delete from abc where id=%s',[i])
    return redirect ("page")

abc 是表名。

page 将是我们在删除产品或条目后要返回的位置。

记得在 views.py 中导入一个库:

from django.db import connection

如果您不导入连接,您的光标将不起作用。

它会从您的 HTML 页面以及数据库中删除特定产品。

于 2019-10-06T11:00:31.547 回答
0

从 Django 中的表中删除一行的简单解决方案

网址.py

url(r'^Books_Admin/$', views.Books_Admin,name="Books_Admin"),

url(r'^BookInfoDelete/(?P<Isbn>\w+)/$', views.BookInfoDelete,name="BookInfoDelete"), 

/* Isbn 是表的主键。*/

视图.py

from django.shortcuts import render,redirect
from .models import BookInfo

def Books_Admin(request):
        books = BookInfo.objects.all()
        return render(request,"Books_Admin.html",{'books':books})

def BookInfoDelete(request,Isbn):
    if request.method == 'POST':
        BookInfo.objects.filter(Isbn=Isbn).delete()
        return redirect(' After deletion which page you want to see, put that url here in sigle qoutes ')

// 这里 BookInfo 是表名。// 这里 Books_Admin 定义用于查看表 BookInfo

模型.py

from django.db import models

class BookInfo(models.Model):
    Isbn = models.CharField(max_length=20, primary_key = True)
    Book_Name = models.CharField(max_length=200)
    Author = models.CharField(max_length=100)
    Publisher = models.CharField(max_length=150)
    Availability = models.CharField(max_length=15)

// 创建表 BookInfo

html

<table class="table table-hover tab">
            <thead>
              <tr>
                <th>ISBN</th>
                <th>Book Name</th>
                <th>Author</th>
                <th>Publisher</th>
              </tr>
            </thead>
            {% for Books in books %}
              <tr>
                <td>{{ Books.Isbn }}</td>
                <td>{{ Books.Book_Name }}</td>
                <td>{{ Books.Author }}</td>
                <td>{{ Books.Publisher }}</td>
                <td>
                  <form action="/BookInfoDelete/{{ Books.Isbn }}/" method="post">
                    {% csrf_token %}
                    <button type="submit" class="btn btn-danger"><span class="glyphicon glyphicon-trash"></span></button>
                </form>
                </td>
              </tr>
            {% endfor %}
          </table>

于 2018-10-07T10:49:48.997 回答