Django中如何完成easyUI 表格数据的增删改?

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaogis/article/details/77481105

摘要:Django是Python中很流行的web框架,本文介绍django 中如何利用easyUI实现数据表格的增删改
系统界面:
系统界面
1. 创建django应用(省略)
2. django与MySQL联接
2.1设置数据库
在setting中设置数据库连接
我用的MySQL

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME':'mydjango',
        'USER':'root',
        'PASSWORD': 'xxxxx',
        'HOST':'127.0.0.1',
        'PORT':'3306',
    }
}

再在项目的根目录中的
init文件

import pymysql

pymysql.install_as_MySQLdb()

2.2创建数据表
在models中

class News(models.Model):
    title = models.CharField(max_length=100)
    date = models.CharField(max_length=20)
    detail_time = models.CharField(max_length=20)
    content = models.TextField()
    url = models.URLField()
    source = models.CharField(max_length=50)
    web = models.CharField(max_length=50)
    logtime = models.CharField(max_length=30)

cmd中完成数据表格创建

#第一步
python manage.py makemigrations [appname] 
#第二步
python manage.py migrate [appname]

3. 主要应用代码
3.1 前端页面代码 info.html
注:请忽略截图中的地图,这部分代码没有在html中,但不影响应用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>在线灾情监测</title>
    <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/icon.css">
    <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/themes/color.css">
    <link rel="stylesheet" type="text/css" href="https://www.jeasyui.com/easyui/demo/demo.css">
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="https://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
<!--各种样式-->
    <style>
        .my-map{float:left; width: 50%; height: 600px;}
        .amap-container{height: 100%;}
        .text_title{margin: auto auto 10px 0; background: #2fa8ec; text-align:center}
    </style>
</head>
<body >
    <h1 class="text_title">互联网新闻</h1>
<div class=" my-map">
    <table id="dg" title="新闻列表" class="easyui-datagrid" style="width:100%;height:600px;"
            url="/read/"
            toolbar="#toolbar" pagination="true"
            rownumbers="true" fitColumns="true" singleSelect="true">
        <thead>
            <tr>
                <th field="news_title" width="50">新闻标题</th>
                <th field="news_date" width="50">日期</th>
                <th field="news_detail_time" width="50">时间</th>
                <th field="news_content" width="50">新闻内容</th>
                <th field="news_url" width="50">url地址</th>
                <th field="news_source" width="50">发布者</th>
                <th field="news_web" width="50">来源网站</th>
                <th field="news_logtime" width="50">获取时间</th>
            </tr>
        </thead>
    </table>
</div>
    <div id="toolbar">
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-add" plain="true" onclick="newNews()">新增新闻</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-edit" plain="true" onclick="editNews()">编辑新闻</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-remove" plain="true" onclick="destroyNews()">移除新闻</a>
    </div>

    <div id="dlg" class="easyui-dialog" style="width:400px"
            closed="true" buttons="#dlg-buttons">
        <form id="fm" method="post" novalidate style="margin:0;padding:20px 50px">
            <div style="margin-bottom:20px;font-size:20px;border-bottom:1px solid #ccc">新闻详情</div>
            <div style="margin-bottom:10px">
                <input name="news_title" class="easyui-textbox" required="true" label="新闻标题:" style="width:100%">
            </div>
            <div style="margin-bottom:10px">
                <input name="news_date" class="easyui-textbox" required="true" label="日期:" style="width:100%">
            </div>
            <div style="margin-bottom:10px">
                <input name="news_detail_time" class="easyui-textbox" required="true" label="时间:" style="width:100%">
            </div>
            <div style="margin-bottom:10px">
                <input name="news_content" class="easyui-textbox" required="true" label="新闻内容:" style="width:100%">
            </div>
            <div style="margin-bottom:10px">
                <input name="news_url" class="easyui-textbox" required="true" label="url地址:" style="width:100%">
            </div>
            <div style="margin-bottom:10px">
                <input name="news_source" class="easyui-textbox" required="true" label="发布者:" style="width:100%">
            </div>
            <div style="margin-bottom:10px">
                <input name="news_web" class="easyui-textbox" required="true"  label="来源网站:" style="width:100%">
            </div>
            <div style="margin-bottom:10px">
                <input name="news_logtime" class="easyui-textbox" required="true"  label="获取时间:" style="width:100%">
            </div>
        </form>
    </div>
    <div id="dlg-buttons">
        <a href="javascript:void(0)" class="easyui-linkbutton c6" iconCls="icon-ok" onclick="saveNews()" style="width:90px ">保存</a>
        <a href="javascript:void(0)" class="easyui-linkbutton" iconCls="icon-cancel" onclick="javascript:$('#dlg').dialog('close')" style="width:90px" >取消</a>
    </div>


    <!--引入表格-->
    <!--<script src="../static/js/table.js"></script>-->
    <script type="text/javascript">
        var url;
        //显示编辑框
        function newNews(){
        $('#dlg').dialog('open').dialog('center').dialog('setTitle','新增新闻');
        $('#fm').form('clear');
        url = '/start/';
        }
        //编辑新闻
        function editNews(){
        var row = $('#dg').datagrid('getSelected');
        console.log(row);
        if (row){
            $('#dlg').dialog('open').dialog('center').dialog('setTitle','Edit News');
            $('#fm').form('load',row);
            //  ajax 编辑News 并且 通过ajax 保存到后端 SQL
            url = '/edit/'+row.news_id;
        }
        }
        // 保存新闻
        function saveNews(){
        $('#fm').form('submit',{
            url: url,
            onSubmit: function(){
                return $(this).form('validate');
            },
            success: function(result){
                if (result=="save"){
                   $('#dlg').dialog('close');
                    $('#dg').datagrid('reload');
                }else
                if (result.errorMsg){
                    $.messager.show({
                        title: 'Error',
                        msg: result.errorMsg
                    });
                } else {
                    $('#dlg').dialog('close');        // close the dialog
                    $('#dg').datagrid('reload');    // reload the News data
                }
            }
        });
        }


        //删除新闻
        function destroyNews(){
        var row = $('#dg').datagrid('getSelected');
        console.log(row);
        if (row){
            $.messager.confirm('再次确认','你确定要删除这条新闻?',function(r){
                if (r){
                    $.ajax({
                        url: '/remove/',
                        type: 'POST',
                        data: {'id':row.news_id},
                        success: function(data) {
                            if (data=="REMOVE"){
                                $('#dg').datagrid('reload');
                            }
                        },
                        error: function(data) {alert("error")}
                    });
                }
            });
        }
        }
</body>
</html>

3.2 后台url.py中代码

from django.conf.urls import url
from django.contrib import admin
from blog import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^index/', views.index),
    url(r'^start/', views.app_start),
    url(r'^read/', views.Read_all_SQL),
    url(r'^edit/(?P<id>\d+)', views.Edit_NewsName),
    url(r'^remove/', views.Remove_News_ID),
]

3.3 后台views.py代码

from django.shortcuts import render, HttpResponse, HttpResponseRedirect
from blog import models
import json
import importlib, sys
importlib.reload(sys)

# Create your views here.
# indexl  &
def index(request):
    return HttpResponseRedirect("http://127.0.0.1:8000/start/")

# 查询数据库中的数据,并构造成json

def Read_all_SQL(request):
    # 查询数据
    obj_all = models.News.objects.all()
    eaList = []
    for li in obj_all:
        eaList.append({
                     "news_title": li.title,
                     "news_date": li.date,
                     "news_detail_time": li.detail_time,
                     "news_content": li.content,
                     "news_url": li.url,
                     "news_source": li.source,
                     "news_web": li.web,
                     "news_logtime": li.logtime,
                     "news_id": li.id})

    # 将int类型使用dumps()方法转为str类型
    eaList_len = json.dumps(len(eaList))
    # 构造一个字典
    json_data_list = {'rows': eaList, 'total': eaList_len}
    # dumps()将字典转变为json形式,
    easyList = json.dumps(json_data_list)
    # 将json返回去,json的键值对中的键需要与前台的表格field=“X”中的X名称保持一致)
    return HttpResponse(easyList)

# 编辑数据并post方法提交到数据库
def Edit_NewsName(request, id):
    print("这是编辑的:"+id)
    print(request.method)
    # 从前端获取到输入的数据
    # POST.get('xxx')这个中的字段是前端表格的<th field="news_title" width="50">新闻标题</th>中的field一致
    if request.method == 'POST':
        title = request.POST.get('news_title')
        date = request.POST.get('news_date')
        detail_time = request.POST.get('news_detail_time')
        content = request.POST.get('news_content')
        url = request.POST.get('news_url')
        source = request.POST.get('news_source')
        web = request.POST.get('news_web')
        logtime = request.POST.get('news_logtime')
        # 构造字典并转成json,这里的键需要与数据库的字段一致
        dic = {
                "title": title,
                "date": date,
                "detail_time": detail_time,
                "content": content,
                "url": url,
                "source": source,
                "web": web,
                "logtime": logtime,
               };
        print(dic)
        models.News.objects.filter(id=id).update(**dic)
        return HttpResponse("Edit_OK")

# 增加数据与start_app
def app_start(request):
    # add_save_News
    if request.method == "POST":
        print("POST")
        print(request.POST)
        title = request.POST.get('news_title')
        date = request.POST.get('news_date')
        detail_time = request.POST.get('news_detail_time')
        content = request.POST.get('news_content')
        url = request.POST.get('news_url')
        source = request.POST.get('news_source')
        web = request.POST.get('news_web')
        logtime = request.POST.get('news_logtime')
        # 构造字典并转成json,这里的键需要与数据库的字段一致
        dic = {
                "title": title,
                "date": date,
                "detail_time": detail_time,
                "content": content,
                "url": url,
                "source": source,
                "web": web,
                "logtime": logtime,
               };
        models.News.objects.create(**dic)
        return HttpResponse("save")
    else:
        print(" is null_!")
    return render(request, 'info.html')

# 移除数据
def Remove_News_ID(request):
    if request.method == "POST":
        print("REMOVE POST")
        id = request.POST.get('id')
        print(id)
        models.News.objects.filter(id=id).delete()
    return HttpResponse("REMOVE")

注意:ajax在交互数据时候涉及到CSRF安全防护的问题,可以在setting.py中禁用相关的模块 # ‘django.middleware.csrf.CsrfViewMiddleware’,

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

参考资料:http://www.cnblogs.com/python-diy/p/7056754.html

展开阅读全文

没有更多推荐了,返回首页