零零碎碎bootstarp-刪除二次確定提示框

有些列表數據需要刪除,但是又不能做到點擊後直接刪除,因爲這樣容易導致誤刪,所以需要提供二次確定提示框,用戶點擊確定刪除後,邏輯刪除數據。點擊取消或x後,取消刪除操作。

方法一:通過模態框來實現

employee_mange.py

<!--用戶列表表單-->
      <div class="row" style="padding-top: 10px; width: 100%">
          <div class="col-md-12">
              <table class="table table-striped">
                  <thead>
                  <tr>
                      <th>id</th><th>姓名</th><th>職能</th><th>狀態</th><th>操作</th>
                  </tr>
                  </thead>
                  <tbody>
                   {% for employee in employees %}
                  <tr>
                      <td>{{employee.id}}</td>
                      <td>{{employee.name}}</td>
                      <td>{{employee.type}}</td>
                      <td>{{employee.del_status}}</td>
                      <td>
                          <a href="/index/{{employee.id}}/" target="{{employee.id}}_blank">修改</a>
                           <!-- 刪除操作觸發模態框 -->
                          <a href="#" onclick="del_employee({{employee.id}})">刪除</a>
                      </td>
                  </tr>
                  {% endfor %}
                  </tbody>
              </table>
          </div>
      </div>

追加同一個頁面,針對刪除操作的腳本語句


<script type="text/javascript">
    $("#delEmployeeModal").modal("hide");//加載頁面首先隱藏模態框,指向模態框的ID
    function del_employee(emp_id){
        $("#delEmployeeModal").modal("show");//顯示模態框
        $('#employee_id').val(emp_id);
<!--        alert("你即將刪除用戶"+emp_id)-->
    }
</script>

 <script type="text/javascript">
$("#del_id").click(function(){
    var eID = $("#employee_id").val();
    javascript:location.href='/employee_del_action/'+eID;
    })
</script>

以上爲用戶列表頁面代碼

views.py

# 刪除用戶
@login_required
def employee_del_action(request, employee_id):
    result = Employee.objects.filter(id=employee_id)
    if not result:
        return render(request, 'employee_manage.html', {'employee.name': result.name, 'hint': '該用戶不存在'})
    result = Employee.objects.filter(id=employee_id, del_status=1)
    if result:
        return render(request, 'employee_manage.html', {'employee.name': result.name, 'hint': '該用戶已被刪除,請勿重複操作'})
    else:
        Employee.objects.select_for_update().filter(id=employee_id).update(del_status=1)
        response = HttpResponseRedirect('/employee_manage/')
        return response

以上views.py中描述的刪除用戶的函數中,提示語句暫時未能實現。目前方法一隻能實現正常刪除數據。

添加路由地址

url.py

"""ManagerPlan URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, re_path
from plan import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),  # 添加index路徑配置
    path('employee_manage/', views.employee_manage),  # 添加角色列表路徑
    path('plan/', views.plan),  # 添加圖片路徑配置
    path('login_action/', views.login_action),  # 添加登錄跳轉路徑配置
    path('plan_manage/', views.plan_manage),  # 添加計劃管理路徑配置
    path('account/login/', views.index),  # 添加訪問非登錄頁面時,指引跳轉到登錄路徑配置
    path('search_content/', views.search_content), # 查詢內容路徑
    path('search_employee/', views.search_employee),  # 查詢用戶路徑
    path('employee_add/', views.employee_add), # 新增用戶頁面路徑
    path('employee_add_action/', views.employee_add_action),  # 新增用戶路徑
    path('content_tag/', views.content_tag),  # 退出
    re_path('employee_del_action/(?P<employee_id>[0-9]+)/', views.employee_del_action),  # 新增用戶路徑
    path('logout/', views.logout),  # 退出
]

用正則法匹配,一直無法匹配到正確到地址,發現,原來用path是行不通到,要引入re_path
re_path(‘employee_del_action/(?P<employee_id>[0-9]+)/’, views.employee_del_action), # 新增用戶路徑
實現效果如下:
在這裏插入圖片描述

拓展:
如果遇上路徑和轉換器語法都不足以定義的URL模式,那麼就需要使用正則表達式,這時候就需要使用re_path(),而非path()。

舉例:傳遞 數字結尾的參數

re_path(r'(\d+)/$',views.peopleList,name='peopleList'),

在這裏插入圖片描述

在這裏插入圖片描述
在這裏插入圖片描述
python正則表達式可詳見這篇文章:Python系列之正則表達式詳解

方法二:通過ajax來處理刪除操作
參考文章:Django實現文章刪除功能
ajax url 路徑寫法
layer關閉彈窗(多種關閉彈窗方法)

plan_manage.html


 <head>
     <meta charset="utf-8">
     {% load bootstrap3 %}
     {% bootstrap_css %}
     {% bootstrap_javascript %}
     <title> 計劃管理系統</title>
     <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
     <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
     <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
     <script type="text/javascript" src="/static/js/layer/layer.js"></script>
 </head>
 <!--............ 中間省略,以下爲body裏面的內容-->
 
      <!--需求列表表單-->
      <div class="row" style="padding-top: 10px; width: 100%">
          <div class="col-md-12">
              <table class="table table-striped">
                  <thead>
                  <tr>
                      <th>id</th><th>需求</th><th>優先級</th><th>測試</th><th>開發</th><th>需求</th>
                      <th>期望上線</th><th>上線時間</th><th>狀態</th><th>項目</th><th>刪除狀態</th><th>創建時間</th><th>修改時間</th>
                      <th>備註</th><th>操作</th>
<!--                      <th>url</th>-->
                  </tr>
                  </thead>
                  <tbody>
                   {% for requirement in requirements %}
                  <tr>
                      <td>{{requirement.id}}</td>
                      <td>{{requirement.content}}</td>
                      <td>{{requirement.emergenyLevel}}</td>
                      <td>{{requirement.tester}}</td>
                      <td>{{requirement.dever}}</td>
                      <td>{{requirement.requirer}}</td>
                      <td>{{requirement.expentedTime}}</td>
                      <td>{{requirement.onlineTime}}</td>
                      <td>{{requirement.online_status}}</td>
                      <td>{{requirement.project}}</td>
                      <td>{{requirement.del_status}}</td>
<!--                      <td>{{requirement.url}}</td>-->
                      <td>{{requirement.create_time}}</td>
                      <td>{{requirement.update_time}}</td>
                      <td>{{requirement.remarks}}</td>
                      <td>
                          <a href="/index/{{employee.id}}/" target="{{employee.id}}_blank">詳情</a>
                          <a href="/index/{{employee.id}}/" target="{{employee.id}}_blank">修改</a>
                          <a href="#" onclick="del_requirement(this, {{requirement.id}})">刪除</a>
                      </td>
                  </tr>
                  {% endfor %}
                  </tbody>
              </table>
          </div>
      </div>

追加與上述同個頁面,刪除操作的腳本處理

<script>
function del_requirement(the, requirement_id){
var article_name = $(the).parents("tr").children("td").eq(1).text();
        var index =layer.open({
        type: 1,
        skin: "layui-layer-rim",
        area: ["400px", "200px"],
        title: "刪除需求",
        content: '<div class="text-center" style="margin-top:30px"><p>刪除內容:《'+article_name+'》</p></div>',
        btn:['確定', '取消'],
        yes: function(){
            layer.close(index);
        $.ajax({
            url: '/requirement_del_action/',
            type:"POST",
            data: {"requirement_id":requirement_id},
            success: function(e){
if (e=="1")
{
<!--    不知道爲什麼提示語一閃而過,想要提示語提示2秒後隱藏,刷新頁面-->
    layer.msg("刪除成功", {icon: 6, time: 2000} ,function(){
    parent.location.reload();
        });
}
else if (e=="2")
{
    layer.msg("刪除失敗", {icon: 6, time: 2000} ,function(){
    parent.location.reload();
        });
}
else if (e=="3")
{
    layer.msg("該內容不存在", {icon: 6, time: 2000} ,function(){
    parent.location.reload();
        });
}
else if (e=="4")
{
    layer.msg("該內容已被刪除,請不要重複操作", {icon: 6, time: 2000} ,function(){
    parent.location.reload();
    });
}
else
{
  layer.msg("系統異常");
}


            },
        })
        },
    });
    }
</script>

需要在views.py添加視圖函數。

views.py

from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST
# .......中間部分其他內容省略
@login_required
@require_POST
@csrf_exempt
def requirement_del_action(request):
    requirement_id = request.POST['requirement_id']
    result = Requirement.objects.get(id=requirement_id)
    if not result:
        return HttpResponse("3")
    result = Requirement.objects.filter(id=requirement_id, del_status=1)
    if result:
        return HttpResponse("4")
    else:
        try:
            Requirement.objects.select_for_update().filter(id=requirement_id).update(del_status=1)
            return HttpResponse("1")
        except:
            return HttpResponse("2")

在urls.py中添加:
path(‘requirement_del_action/’, views.requirement_del_action), # 刪除需求內容路徑

urls.py


from django.contrib import admin
from django.urls import path, re_path
from plan import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),  # 添加index路徑配置
    path('employee_manage/', views.employee_manage),  # 添加角色列表路徑
    path('plan/', views.plan),  # 添加圖片路徑配置
    path('login_action/', views.login_action),  # 添加登錄跳轉路徑配置
    path('plan_manage/', views.plan_manage),  # 添加計劃管理路徑配置
    path('requirement_add/', views.requirement_add),  # 增加需求頁面路徑
    path('requirement_add_action/', views.requirement_add_action),  # 增加需求內容路徑配置
    path('account/login/', views.index),  # 添加訪問非登錄頁面時,指引跳轉到登錄路徑配置
    path('search_content/', views.search_content), # 查詢內容路徑
    path('search_employee/', views.search_employee),  # 查詢用戶路徑
    path('employee_add/', views.employee_add), # 新增用戶頁面路徑
    path('employee_add_action/', views.employee_add_action),  # 新增用戶路徑
    path('content_tag/', views.content_tag),  # 退出
    re_path('employee_del_action/(?P<employee_id>[0-9]+)/', views.employee_del_action),  # 新增用戶路徑
    path('requirement_del_action/', views.requirement_del_action),  # 刪除需求內容路徑
    re_path('requirement_detail/(?P<employee_id>[0-9]+)/', views.employee_del_action),  # 新增用戶路徑
    path('logout/', views.logout),  # 退出
]

遇到的問題:
問題1、Uncaught ReferenceError: layer is not defined
在這裏插入圖片描述
解決辦法:缺少js的引入(js/layer.js)
直接下載layer.js,然後在當前要使用的項目中引入
在這裏插入圖片描述
在settings.py中添加js


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static')
STATICFILES_DIRS = (
    ('css', os.path.join(STATIC_ROOT, 'css').replace('\\', '/')),
    ('js', os.path.join(STATIC_ROOT, 'js').replace('\\', '/')),
    ('images', os.path.join(STATIC_ROOT, 'images').replace('\\', '/')),
)

記得重啓項目
python3 manage.py runserver
並清除瀏覽器緩存,重新訪問。

刪除參考:
https://blog.csdn.net/chengqiuming/article/details/85310298

問題2:
如何獲取要刪除的內容標題?
方法如下:

var article_name = $(the).parents("tr").children("td").eq(1).text();
        title: "刪除需求",
        content: '<div class="text-center" style="margin-top:30px"><p>刪除內容:《'+article_name+'》</p></div>',
        btn:['確定', '取消'],

問題3:
layer.msg不知道爲什麼提示語一閃而過,想要提示語提示2秒後隱藏,刷新頁面
1)、如何在點擊確定的時候,就隱藏layer
將layer.open打開後的索引賦值給某個變量,然後通過layer.close(index)的方法關閉。
2)、如何讓提示語在2s後消失,並且自動刷新頁面
在plan_manage.py中涉及刪除操作的script腳本中按此處理(詳見以上具體代碼)

layer.msg("刪除成功", {icon: 6, time: 2000} ,function(){
    parent.location.reload();
        });

實現後效果如下:
在這裏插入圖片描述
點擊確定後:
在這裏插入圖片描述

接下來,要處理:如何實現點擊【詳情】展示內容詳情。
參考文章:Django實現點擊詳情跳轉新界面、路由名稱和分發3

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章