bootstap datatable显示未找到的匹配记录Django

发布于 2025-01-30 19:11:12 字数 5803 浏览 2 评论 0原文

我正在Django开发一个项目,用户可以共享文件。我从数据库中检索数据(文件),并在模板上的表中显示它,并使用Bootstrap DataTable在表中实现搜索功能,但是当我从DataTable中搜索任何记录时,它显示我未找到

Bootstrap DataTable CSS CDN

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css">

bootstrap DataTable JavaScript cdn

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap4.min.js"></script>

bootstrap脚本以显示html表中的数据表功能

<script>
    $(document).ready(function() {
     $('#datatable').DataTable();

    } );

    </script> 

template template代码:


{% extends 'instructor/admin_base.html' %}
    {% load static %}
    {% block body %}
    <div id="page-container" >
    <main id="main-container">
    <div class="content"> 
    <h3 class="text-center notesText">All Notes</h3><br> 
    `<div class="tablecss container  mt-5" ><div >
    <!--id="datatable" is used for implementing boostrap dataTable features in table-->
    <table id="datatable" class=" table table-bordered table-striped table-vcenter js-dataTable-full-pagination" style=" color:gray;">
                  

    <thead style="background-color : #607d8b; color:white;" >
                    <tr>
                        <th>S.No</th>
                        <th>Uploading Date</th>
                        <th>Branch</th>
                        <th>Subject</th>
                        <th>Download Notes</th>
                        <th>File Type</th>
                        <th>Description</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </th

    {% for i in notes %}
                <tbody>
                <tr>
                  <td>{{forloop.counter}}</td>
                    <td>{{i.uploadingdate}}</td>
                    <td>{{i.branch}}</td>
                    <td>{{i.subject}}</td>
                    <td><a href="{{i.notesfile.url}}" class="btn btn-success" download>Download</a></td>
                    <td>{{i.filetype}}</td>
                    <td>{{i.description}}</td>
                    <td>{{i.status}}</td>
                
                    <td><a href="{% url 'dashboard:delete_notes' i.id %}" class="btn btn-danger" onclick="return confirm('Are your sure to Delete ?')">Delete</a></td>
                    
                </tr>
                {% endfor %}
                </tbody>
    </table>
    </div>
    </div>`</div>`
    </main>
    </div>

views.pys.py(我在哪个我'd想要实现搜索函数)

def all_notes(request):
    if not request.user.is_authenticated:
        return redirect('login_admin')
    notes = Upload_Notes.objects.all()
    context = {'notes':notes}
    return render(request, 'instructor/all_notes.html',context)

dashboard/urls.py:

from django.contrib import admin
from django.urls import path
from . import views
app_name="dashboard"
urlpatterns=[
    path('pending_notes', views.pending_notes, name='pending_notes'),
    path('assign_status/<int:pk>', views.assign_status, name='assign_status'),
    path('accepted_notes', views.accepted_notes, name='accepted_notes'),
    path('rejected_notes', views.rejected_notes, name='rejected_notes'),
    path('all_notes', views.all_notes, name='all_notes'),
    path('admin_home',views.admin_home,name="admin_home"),
    path("showallusers", views.show_all_users, name="showallusers"),

]

models.py


class Upload_Notes(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    uploadingdate = models.CharField(max_length=30)
    branch = models.CharField(max_length=30)
    subject = models.CharField(max_length=50)
    notesfile = models.FileField(null=True,validators=(validate_file_extension,))
    filetype = models.CharField(max_length=30)
    description = models.CharField(max_length=200, null=True)
    status = models.CharField(max_length=15)
    def __str__(self):
        return f'{self.user} notes'

delete_notes视图

def delete_notes(request,pk=None):
if not request.user.is_authenticated:
    return redirect('login')
notes = Upload_Notes.objects.get(id=pk)
notes.delete()
messages.success(request,f"  Notes  delated  successfully!")
return  redirect('/all_notes')

all_notes我有3种其他用于显示pendend_notes的方法, accepped_notes 和reconded_notes

带有错误消息的模板映像<代码>找不到匹配记录

额外: DataTable在我显示所有用户信息的另一个表中可以完美地工作。我找不到问题表在笔记表中不起作用的问题。

I am developing a project in Django where users can share files. I retrieve data(files) from the database and show it in a table on the template and use bootstrap DataTable to implement search functionality in my table But when I search any record from DataTable it shows me No matching records found.

Bootstrap Datatable CSS CDN

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css">

Bootstrap Datatable Javascript CDN

<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap4.min.js"></script>

Bootstrap script to show data table functionality in a HTML table

<script>
    $(document).ready(function() {
     $('#datatable').DataTable();

    } );

    </script> 

Template Code:


{% extends 'instructor/admin_base.html' %}
    {% load static %}
    {% block body %}
    <div id="page-container" >
    <main id="main-container">
    <div class="content"> 
    <h3 class="text-center notesText">All Notes</h3><br> 
    `<div class="tablecss container  mt-5" ><div >
    <!--id="datatable" is used for implementing boostrap dataTable features in table-->
    <table id="datatable" class=" table table-bordered table-striped table-vcenter js-dataTable-full-pagination" style=" color:gray;">
                  

    <thead style="background-color : #607d8b; color:white;" >
                    <tr>
                        <th>S.No</th>
                        <th>Uploading Date</th>
                        <th>Branch</th>
                        <th>Subject</th>
                        <th>Download Notes</th>
                        <th>File Type</th>
                        <th>Description</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </th

    {% for i in notes %}
                <tbody>
                <tr>
                  <td>{{forloop.counter}}</td>
                    <td>{{i.uploadingdate}}</td>
                    <td>{{i.branch}}</td>
                    <td>{{i.subject}}</td>
                    <td><a href="{{i.notesfile.url}}" class="btn btn-success" download>Download</a></td>
                    <td>{{i.filetype}}</td>
                    <td>{{i.description}}</td>
                    <td>{{i.status}}</td>
                
                    <td><a href="{% url 'dashboard:delete_notes' i.id %}" class="btn btn-danger" onclick="return confirm('Are your sure to Delete ?')">Delete</a></td>
                    
                </tr>
                {% endfor %}
                </tbody>
    </table>
    </div>
    </div>`</div>`
    </main>
    </div>

Views.py (In which I'd like to implement search functinality)

def all_notes(request):
    if not request.user.is_authenticated:
        return redirect('login_admin')
    notes = Upload_Notes.objects.all()
    context = {'notes':notes}
    return render(request, 'instructor/all_notes.html',context)

dashboard/urls.py:

from django.contrib import admin
from django.urls import path
from . import views
app_name="dashboard"
urlpatterns=[
    path('pending_notes', views.pending_notes, name='pending_notes'),
    path('assign_status/<int:pk>', views.assign_status, name='assign_status'),
    path('accepted_notes', views.accepted_notes, name='accepted_notes'),
    path('rejected_notes', views.rejected_notes, name='rejected_notes'),
    path('all_notes', views.all_notes, name='all_notes'),
    path('admin_home',views.admin_home,name="admin_home"),
    path("showallusers", views.show_all_users, name="showallusers"),

]

Models.py


class Upload_Notes(models.Model):
    user = models.ForeignKey(User,on_delete=models.CASCADE)
    uploadingdate = models.CharField(max_length=30)
    branch = models.CharField(max_length=30)
    subject = models.CharField(max_length=50)
    notesfile = models.FileField(null=True,validators=(validate_file_extension,))
    filetype = models.CharField(max_length=30)
    description = models.CharField(max_length=200, null=True)
    status = models.CharField(max_length=15)
    def __str__(self):
        return f'{self.user} notes'

delete_notes view

def delete_notes(request,pk=None):
if not request.user.is_authenticated:
    return redirect('login')
notes = Upload_Notes.objects.get(id=pk)
notes.delete()
messages.success(request,f"  Notes  delated  successfully!")
return  redirect('/all_notes')

Like all_notes I have 3 other method for displaying pending_notes ,accepted_notes and rejected_notes.

Template image with error message no matching record found
image

Extra:
Datatable is working perfectly in another table where I am showing all user info.I am not able to find the problem why data table is not working in the notes table.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

很快妥协 2025-02-06 19:11:12

您只需检查 ajax [MDN-REFERY] ,简而言之,Ajax为我们提供了在网页中进行CRUD操作的功能,而无需重新加载页面。

在您的代码中,您可以通过以下方式实现无需重新加载页面的删除功能:

模板文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css">
</head>
<body>
<div id="page-container" >
    <main id="main-container">
    <div class="content"> 
    <h3 class="text-center notesText">All Notes</h3><br> 
    <div class="tablecss container  mt-5" ><div>
          <div class="alert alert-success alert-dismissible fade show" role="alert">
            <p class="main-message"></p>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
              <span aria-hidden="true">×</span>
            </button>
          </div>
    <!--id="datatable" is used for implementing boostrap dataTable features in table-->
    <table id="datatable" class=" table table-bordered table-striped table-vcenter js-dataTable-full-pagination" style=" color:gray;">
             
   

    <thead style="background-color : #607d8b; color:white;" >
        {% csrf_token %}
                    <tr>
                        <th>S.No</th>
                        <th>Uploading Date</th>
                        <th>Branch</th>
                        <th>Subject</th>
                        <th>Download Notes</th>
                        <th>File Type</th>
                        <th>Description</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </th
    
    {% for i in notes %}
                <tbody>
                <tr>
                    <td>{{forloop.counter}}</td>
                    <td>{{i.uploadingdate}}</td>
                    <td>{{i.branch}}</td>
                    <td>{{i.subject}}</td>
                    <td><a href="{{i.notesfile.url}}" class="btn btn-success" download>Download</a></td>
                    <td>{{i.filetype}}</td>
                    <td>{{i.description}}</td>
                    <td>{{i.status}}</td>
                
                    <td><button notesid="{{i.id}}" class="btn btn-danger remove-notes">Delete</button></td>
                    
                </tr>
                {% endfor %}
                </tbody>
    </table>
    </div>
    </div></div>
    </main>
    </div>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap4.min.js"></script>
 
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        
    <script>
                    let messageBox =document.getElementsByClassName("alert-success")[0].children[0];
            if (messageBox.innerHTML == "") {
            console.log(messageBox.parentNode);
            messageBox.parentNode.style.display = "none";
            }

            // main jquery ajax function
            $(".remove-notes").click(function () {
            confirmation = confirm("Are you sure to delete");
            if (confirmation) {
                let elm = this;
                let id = elm.getAttribute("notesid").toString();
                console.log(id);

                $.ajaxSetup({
                headers: {
                    "X-CSRFToken": $("[name=csrfmiddlewaretoken]").val(),
                },
                });
                console.log(id);
                $.ajax({
                type: "POST",
                url: "{% url 'dashboard:delete_notes' %}",

                data: {
                    notesid: id,
                },
                success: function (resp) {
                    // console.log(status);
                    // resp means response
                    console.log("data is coming");
                    console.log(resp.msg);
                    elm.parentNode.parentNode.remove();
                    if (resp.msg != "") {
                    let messageBox = document.getElementsByClassName("alert-success")[0].children[0];
                    messageBox.parentNode.style.display = "block";
                    messageBox.innerHTML = resp.msg;
                    }
                },
                error: function (resp) {
                    console.log(resp);
                },
                });
            }
            });

    </script>
        </body>
        </html>

views.py

def all_notes(request):
    if not request.user.is_authenticated:
        return redirect('login_admin')
    notes = Upload_Notes.objects.all()
    context = {'notes': notes}
    return render(request, 'dashboard/all_notes.html', context)


def delete_notes(request, pk=None):
    if request.method == 'POST':
        if not request.user.is_authenticated:
            return redirect('login')
        print(request.POST.get('notesid'))
        notes = Upload_Notes.objects.get(id=int(request.POST.get('notesid')))
        notes.delete()
        return JsonResponse({'msg': 'Notes deleted successfully !'})

urls.py

from django.contrib import admin
from django.urls import path
from . import views
app_name = "dashboard"
urlpatterns = [
    path('all_notes/', views.all_notes, name='all_notes'),
    path('delete-records/', views.delete_notes, name='delete_notes')
]

You can simply check Ajax[mdn-reference], in short ajax gives us the functionality to do CRUD operations in the webpage without reloading the page.

In your code you can implement delete functionality of without reloading page in the following way:

Template file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.2/css/bootstrap.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css">
</head>
<body>
<div id="page-container" >
    <main id="main-container">
    <div class="content"> 
    <h3 class="text-center notesText">All Notes</h3><br> 
    <div class="tablecss container  mt-5" ><div>
          <div class="alert alert-success alert-dismissible fade show" role="alert">
            <p class="main-message"></p>
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
              <span aria-hidden="true">×</span>
            </button>
          </div>
    <!--id="datatable" is used for implementing boostrap dataTable features in table-->
    <table id="datatable" class=" table table-bordered table-striped table-vcenter js-dataTable-full-pagination" style=" color:gray;">
             
   

    <thead style="background-color : #607d8b; color:white;" >
        {% csrf_token %}
                    <tr>
                        <th>S.No</th>
                        <th>Uploading Date</th>
                        <th>Branch</th>
                        <th>Subject</th>
                        <th>Download Notes</th>
                        <th>File Type</th>
                        <th>Description</th>
                        <th>Status</th>
                        <th>Action</th>
                    </tr>
                </th
    
    {% for i in notes %}
                <tbody>
                <tr>
                    <td>{{forloop.counter}}</td>
                    <td>{{i.uploadingdate}}</td>
                    <td>{{i.branch}}</td>
                    <td>{{i.subject}}</td>
                    <td><a href="{{i.notesfile.url}}" class="btn btn-success" download>Download</a></td>
                    <td>{{i.filetype}}</td>
                    <td>{{i.description}}</td>
                    <td>{{i.status}}</td>
                
                    <td><button notesid="{{i.id}}" class="btn btn-danger remove-notes">Delete</button></td>
                    
                </tr>
                {% endfor %}
                </tbody>
    </table>
    </div>
    </div></div>
    </main>
    </div>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap4.min.js"></script>
 
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        
    <script>
                    let messageBox =document.getElementsByClassName("alert-success")[0].children[0];
            if (messageBox.innerHTML == "") {
            console.log(messageBox.parentNode);
            messageBox.parentNode.style.display = "none";
            }

            // main jquery ajax function
            $(".remove-notes").click(function () {
            confirmation = confirm("Are you sure to delete");
            if (confirmation) {
                let elm = this;
                let id = elm.getAttribute("notesid").toString();
                console.log(id);

                $.ajaxSetup({
                headers: {
                    "X-CSRFToken": $("[name=csrfmiddlewaretoken]").val(),
                },
                });
                console.log(id);
                $.ajax({
                type: "POST",
                url: "{% url 'dashboard:delete_notes' %}",

                data: {
                    notesid: id,
                },
                success: function (resp) {
                    // console.log(status);
                    // resp means response
                    console.log("data is coming");
                    console.log(resp.msg);
                    elm.parentNode.parentNode.remove();
                    if (resp.msg != "") {
                    let messageBox = document.getElementsByClassName("alert-success")[0].children[0];
                    messageBox.parentNode.style.display = "block";
                    messageBox.innerHTML = resp.msg;
                    }
                },
                error: function (resp) {
                    console.log(resp);
                },
                });
            }
            });

    </script>
        </body>
        </html>

views.py

def all_notes(request):
    if not request.user.is_authenticated:
        return redirect('login_admin')
    notes = Upload_Notes.objects.all()
    context = {'notes': notes}
    return render(request, 'dashboard/all_notes.html', context)


def delete_notes(request, pk=None):
    if request.method == 'POST':
        if not request.user.is_authenticated:
            return redirect('login')
        print(request.POST.get('notesid'))
        notes = Upload_Notes.objects.get(id=int(request.POST.get('notesid')))
        notes.delete()
        return JsonResponse({'msg': 'Notes deleted successfully !'})

urls.py

from django.contrib import admin
from django.urls import path
from . import views
app_name = "dashboard"
urlpatterns = [
    path('all_notes/', views.all_notes, name='all_notes'),
    path('delete-records/', views.delete_notes, name='delete_notes')
]
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文