基于Python Django框架+jquery Ajax技术实现的增删改查(CRUD)

Django框架优势:

1、开源框架,有完美的文档支持
2、解决方案众多,内部功能支持较多
3、优雅的URL,完整的路由系统
4、自助式ORM机制的后台管理

注:本文章是基于ORM机制进行的Ajax异步增删改查

项目架构

注:’—‘为一级路径,’——‘为二级路径,’———‘为三级路径,’————'为四级路径.

my_django_project(项目名)
—my_django_project(初始文件)
—— settings.py(项目配置文件)
——urls.py(路由表文件)
——wsgi.py(基于WSGI机制)
—shopapp(本文章的app名称,在Terminal 键入python manage.py startapp shopapp命令行生成该文件,包含如下子文件)
——migrations(本文章未对其进行任何操作,可忽略)
——static(该文件中可包含.css子文件以及.js子文件如下)
———js(该文件夹下包含.js文件)
————jquery-3.2.1.min.js(引入了jquery框架)
————shop.js(此文件中包含Ajax的具体应用)
——admin.py(用于注册models文件中的类)
——apps.py(用于注册app文件)
——models.py(可在Terminal 键入python manage.py inspectdb > shopapp/models.py 自动生成settings.py中配置的数据库中的各个表的数据列)
——tests.py(可在此文件中进行测试,本文章未对其操作)
——views.py(包含所有的数据库操作,即(CRUD))
—templates(此文件包含.html文件)
——messageinfo.html(本文章的html文件)
—manage.py(启动Django框架的文件)

:以下文件按照如上所述的顺序进行排列,以便于查看

settings.py文件(包含原有的代码以及修改配置的代码如下):

"""
Django settings for my_django_project project.

Generated by 'django-admin startproject' using Django 2.2.5.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.2/ref/settings/
"""

import os

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'eu!&l#9d5q42k*@p78^zv^-^w6tqqutbp(f&mk5dxjue&=(9v('

SESSION_ENGINE = 'django.contrib.sessions.backends.cache'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    'shopapp.apps.ShopappConfig',
]

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',
]

ROOT_URLCONF = 'my_django_project.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'my_django_project.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
         'ENGINE': 'django.db.backends.mysql',
         'NAME': 'db_job_data',
         'HOST': '你的数据库地址',
         'USER': '你的用户名',
         'PASSWORD':'你的密码',
         'PORT': '你的数据库端口号',
         'OPTIONS':{'isolation_level':None}
    }
}


# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


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

STATIC_URL = '/static/'

STATICFILES_DIRS = (
    os.path.join(BASE_DIR,"static"),   #配置static下的样式文件
)

# 配置输出sql语句
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console':{
            'level':'DEBUG',
            'class':'logging.StreamHandler',
        },
    },
    'loggers': {
        'django.db.backends': {
            'handlers': ['console'],
            'propagate': True,
            'level':'DEBUG',
        },
    }
}

urls.py文件(用于配置路由)

from django.contrib import admin
from django.urls import path
from shopapp.views import *

urlpatterns = [
    path('admin/', admin.site.urls),
    path('',index),  #默认的登陆界面
    path('checkshopname/',checkShopName),
    path('ajaxshopinfo/',getShopInfo),
    path('submits/',submits),

]

shop.js文件(包含Ajax具体代码)

//修改
function submitModifyShop(id) {
    //console.log('#list-line' + id +" td")

    $('#list-lines' + id +" td").attr('contentEditable',true);

// $('#id').attr("readonly","readonly");
}

//点击修改完成按钮的功能
function submitModifyShops(id){
    $.ajax({
    type: 'post',                            // 传数据的方式
    url: 'checkshopname/',
    dataType: 'json',                        // xml、json、script、html
    data:JSON.stringify({
        'shopId': $("td[name='shopId"+id+"']").html(),     //  $('#userName') == document.getElementById('userName')
        'shopName': $("td[name='shopName"+id+"']").html(),
        'shopPrice': $("td[name='shopPrice"+id+"']").html(),
        'shopNum': $("td[name='shopNum"+id+"']").html(),


    }),
    error: function(xhr, err){
        alert('请求失败,请检查,' + err + '!')
    },
    success: function(data, textStatus){    // success对应的回调函数的第一个参数,是服务器返回的数据
        if(data.code==1){
            alert("修改完成!")
            //console.log("成功")
            $('#list-lines' + id +" td").attr('contentEditable',false)

        }
    }
});

}



function getShopData(currentPage, pageSize, opr, shopId) {

    shopName =  document.searchForms.shopName.value


    if(opr == 'del'){
        if(!confirm('确定要删除吗?')){
            return false
        }
    }

    $.ajax({
        type: 'post',                            // 传数据的方式
        url: 'ajaxshopinfo/',
        dataType: 'json',                        // xml、json、script、html
        data:JSON.stringify({
            'shopId':shopId,
            'shopName':shopName,
            'pageSize': pageSize,
            'currentPage': currentPage,
            'opr': opr
        }),
        error: function(xhr, err){
            alert('请求失败,请检查,' + err + '!')
        },
        success: function(data, textStatus){    // success对应的回调函数的第一个参数,是服务器返回的数据
            if(data.code == 1 && opr != 'update'){
                var htmlTexts = ""
                for(var i =0;i <data.shopData.length;i++){
                     htmlTexts +=' <tr id="list-lines'+data.shopData[i]['job_id']+'" >\n' +
                    '                                        <td><input type="checkbox" name="shopId" value='+ data.shopData[i]['job_id'] +'/></td>\n' +
                    '                                        <td name="shopId'+ data.shopData[i]['job_id'] +'">'+ data.shopData[i]['job_id']+'</td>\n' +
                    '                                        <td name="shopName'+ data.shopData[i]['job_id'] +'">'+ data.shopData[i]['jobposition'] +'</td>\n' +
                    '                                        <td name="shopPrice'+ data.shopData[i]['job_id'] +'">'+ data.shopData[i]['job_mmoney'] +'</td>\n' +
                    '                                        <td name="shopNum'+ data.shopData[i]['job_id'] +'">'+ data.shopData[i]['job_city'] +'</td>\n' +
                    '                                        <td>\n' +
                    '                                            <a href="javascript:getShopData(1,16,\'del\','+ data.shopData[i]['job_id'] +');">删除</a>&nbsp;&nbsp;\n' +
                    '                                            <a onclick=submitModifyShop('+ data.shopData[i]['job_id'] +')>修改</a>&nbsp;&nbsp;\n' +
                    '                                            <a onclick=submitModifyShops('+ data.shopData[i]['job_id'] +')>完成</a>\n' +
                    '                                        </td>\n' +
                    '                                        \n' +
                    '                                    </tr>'
                }
                pageTexts = '<tr><td colspan="8" align="center">---------------------------------------------------------------------------------------------------</td></tr>' +
                '<tr><td colspan="8" align="center">'+ '当前第' + data.currentPage + '页&nbsp;&nbsp;总共有' + data.totalPage + '页&nbsp;&nbsp;';
                if(data.currentPage <= 1) {
                    pageTexts += '首页 &nbsp;&nbsp;上一页&nbsp;&nbsp;';
                }else{
                     pageTexts += '<a href="javascript:getShopData(1,16,\'search\', 0);">首页</a> &nbsp;&nbsp;' +
                        '<a href="javascript:getShopData(' + (data.currentPage - 1) + ', 16, \'search\', 0);">上一页</a>&nbsp;&nbsp;';
                }

                if(data.currentPage >= data.totalPage){
                     pageTexts += '下一页&nbsp;&nbsp;尾页&nbsp;&nbsp;';
                }else {
                    pageTexts += '<a href="javascript:getShopData(' + (data.currentPage + 1) + ', 16, \'search\', 0);">下一页</a>&nbsp;&nbsp;' +
                    '<a href="javascript:getShopData(' + data.totalPage + ', 16, \'search\', 0);">尾页</a>&nbsp;&nbsp;';
                }
                pageTexts +='</td></tr>'

                $('#shopDataBody').empty()
                $('#shopDataBody').append(htmlTexts)
                $('#shopDataBody').append(pageTexts)

                document.searchForm.currentPage.value = data.currentPage
                document.searchForm.pageSize.value=data.pageSize
            }

        }
    });
}
$(document).ready(
    function(){
        getShopData(1, 16, 'search', 0)
    }
)


// `asdad${this}asdasd asd ${asd}sada as`

function insert() {
    template = document.getElementById("theTemplate").innerHTML ;
    // console.log(template)//获取index.html界面模态框代码
    $('#model').append(template);
}

function submits(){
    jobposition = $("input[name='jobposition']:first").val()
    jobmoney = $("input[name='jobmoney']:first").val()
    jobcity = $("input[name='jobcity']:first").val()

    $.ajax({
        type: 'post',                            // 传数据的方式
        url: 'submits/',
        dataType: 'json',                        // xml、json、script、html
        data: JSON.stringify({
            'jobposition':jobposition,
            'jobmoney':jobmoney,
            'jobcity':jobcity,

        }),
        error: function (xhr, err) {
            alert('请求失败,请检查,' + err + '!')
        },
        success: function (data, textStatus) {
            if(data.code==1){
                alert("数据写入成功")
            }
        }
    })


}


admin.py文件

from django.contrib import admin

# Register your models here.

from shopapp.models import JobPosition
admin.site.register(JobPosition)

apps.py文件

from django.apps import AppConfig

class ShopappConfig(AppConfig):
    name = 'shopapp'

models.py文件

from django.db import models

class JobPosition(models.Model):
    job_id = models.AutoField(db_column='job_id',primary_key=True)
    jobposition = models.CharField(db_column='jobposition',max_length=100, blank=True, null=True)
    job_mmoney = models.CharField(db_column='job_MMoney', max_length=45, blank=True, null=True)  # Field name made lowercase.
    job_city = models.CharField(db_column='job_city',max_length=128, blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'job_position'

views.py文件(基于ORM机制的增删改查,代码如下)

from django.shortcuts import render
from shopapp.models import JobPosition
from django.http.response import HttpResponse
import json

def index(request):
    return render(request,'messageinfo.html')
    pass

#确认修改
def checkShopName(request):
    shopdata = request.body.decode('utf-8')
    shopDict = json.loads(shopdata)
    shop = JobPosition()
    shop.job_id = shopDict.get('shopId')   #将数据赋给user实体的属性
    shop.jobposition=shopDict.get('shopName')
    shop.job_mmoney = shopDict.get('shopPrice')
    shop.job_city = shopDict.get('shopNum')

    JobPosition.objects.filter(job_id=shop.job_id).update(jobposition=shop.jobposition,job_mmoney=shop.job_mmoney,job_city=shop.job_city)

    return HttpResponse(json.dumps({'code':1}),content_type="application/json")
    pass

#查询以及分页  还有删除
def getShopInfo(request):
    shopData = request.body.decode('utf-8')
    shopDict = json.loads(shopData)

    currentPage = int(shopDict.get('currentPage'))
    pageSize = int(shopDict.get('pageSize'))
    opr = shopDict.get('opr')
    shopId = shopDict.get('shopId')

    if opr=='del':
        shop = JobPosition()
        shop.job_id = shopId
        shop.delete()  #删除

    result = JobPosition.objects.filter(job_city__contains=shopDict.get("shopName")).values("job_id","jobposition","job_mmoney","job_city")[(currentPage-1)*pageSize:pageSize*currentPage]
    counts = JobPosition.objects.filter(job_city__contains=shopDict.get("shopName")).count()
    totalPage = 0
    if(counts%pageSize == 0):
        totalPage = counts//pageSize
    else:
        totalPage = counts // pageSize + 1
        pass

    returnData = {'code':1, 'shopData':json.loads(json.dumps(list(result))), 'pageSize':pageSize, 'currentPage':currentPage, 'totalPage':totalPage, 'opr':'search'}
    return HttpResponse(json.dumps(returnData),content_type="application/json")
    pass

#确认添加
def submits(request):
    Text = request.body.decode('utf-8')
    TextDict = json.loads(Text)
    shop = JobPosition()
    shop.jobposition = TextDict.get('jobposition')
    shop.job_mmoney = TextDict.get('jobmoney')
    shop.job_city= TextDict.get('jobcity')
    shop.save()   #插入实例化对象的三个属性值
    return HttpResponse(json.dumps({'code': 1}),content_type="application/json")
    pass

messageinfo.html代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <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>

    {% load static %}
    <script type="text/javascript" src="{% static "js/shop.js" %}"></script>

</head>

<body>
    <div class="container">
        <h2>管理员界面</h2>
        <br/>
	<div class="row clearfix">
		<div class="col-md-12 column">
			<div class="tabbable" id="tabs-200351">
				<ul class="nav nav-tabs">
					<li>
						 <a href="#panel-200936" data-toggle="tab">数据管理</a>
					</li>
				</ul>
				<div class="tab-content">
					<div class="tab-pane active" id="panel-200936">
						<br/>
                    <!--查询-->
                    <div id="searchBoxs">  <!-- action="/gouserinfo.do" -->
						<form method="post" name="searchForms">
                            <br/>
                            城市名:<input type="text" name="shopName">

                            <input type="hidden" name="currentPage" value="1"/>  <!--hidden为不可见-->
                            <input type="hidden" name="pageSize" value="16"/>
                            <input type="button" value="查询" onclick="getShopData(1, 16, 'search', 0)">

                             <input type="button" value="添加" onclick="insert()" data-toggle="modal" data-target="#myModal">

                        </form>
                    </div>

                    <script type="text/html" id="theTemplate">

{#                    <!-- 按钮触发模态框 -->#}
{#                    <button class="btn btn-primary" data-toggle="modal" data-target="#myModal">#}
{#                        开始演示模态框#}
{#{                   </button>#}
{#                    <!-- 模态框(Modal)-->#}
                    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal"
                                            aria-hidden="true">
                                    </button>
                                    <h2 class="modal-title" id="myModalLabel">
                                        请插入职位信息
                                    </h2>
                                </div>
                                <div class="modal-body">
                                    <div id="orderCon" style="text-align:center">
                                        职位名:&nbsp;&nbsp;<input type="text" name="jobposition" value="" /><br/><br/>
                                        月薪:&nbsp;&nbsp;<input type="text" name="jobmoney" value="" /><br/><br/>
                                        城市:&nbsp;&nbsp;<input type="text" name="jobcity" value="" /><br/><br/>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default"
                                            data-dismiss="modal">关闭
                                    </button>
                                    <button type="button" class="btn btn-primary" id="orderSubmit" onclick="submits()" data-dismiss="modal">
                                        添加
                                    </button>
                                </div>
                            </div><!-- /.modal-content -->
                        </div><!-- /.modal-dialog -->
                    </div><!-- /.modal -->

                </script>
                        <div id="model">
                            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="display: none;">
                        <div class="modal-dialog">
                            <div class="modal-content">
                                <div class="modal-header">
                                    <button type="button" class="close" data-dismiss="modal"
                                            aria-hidden="true">
                                    </button>
                                    <h2 class="modal-title" id="myModalLabel">
                                        请插入职位信息
                                    </h2>
                                </div>
                                <div class="modal-body">
                                    <div id="orderCon" style="text-align:center">
                                        职位名:&nbsp;&nbsp;<input type="text" name="jobposition" value="" /><br/><br/>
                                        月薪:&nbsp;&nbsp;<input type="text" name="jobmoney" value="" /><br/><br/>
                                        城市:&nbsp;&nbsp;<input type="text" name="jobcity" value="" /><br/><br/>
                                    </div>
                                </div>
                                <div class="modal-footer">
                                    <button type="button" class="btn btn-default"
                                            data-dismiss="modal">关闭
                                    </button>
                                    <button type="button" class="btn btn-primary" id="orderSubmit" onclick="submits()" data-dismiss="modal">
                                        添加
                                    </button>
                                </div>
                            </div><!-- /.modal-content -->
                        </div><!-- /.modal-dialog -->
                    </div><!-- /.modal -->
                        </div>

                    <!--动态生成数据库中商品信息的表格-->
                        <table class="dataTables" align="center" style="width: 100%">

                            <thead>
                                <tr>
                                    <th align="center">
                                        <input type="button" value="全选"/>
                                        <input type="button" value="反选"/>
                                    </th>
                                    <th>职位编号</th>
                                    <th>职位名</th>
                                    <th>月薪</th>
                                    <th>城市</th>

                                </tr>
                            </thead>

                            <tbody id="shopDataBody">
{#                            {% for shop in shopList %}#}
{#                               <tr id="list-lines{{ shop.shopId }}" >#}
{#                                      <td><input type="checkboxs" name="shopId" value="{{ shop.shopId }}"/></td>#}
{#                                      <td name="shopId{{ shop.shopId }}">{{ shop.shopId }}</td>#}
{#                                      <td name="shopName{{ shop.shopId }}">{{ shop.shopName }}</td>#}
{#                                      <td name="shopPrice{{ shop.shopId }}">{{ shop.shopPrice }}</td>#}
{#                                      <td name="shopNum{{ shop.shopId }}">{{ shop.shopNum }}</td>#}
{#                                      <td name="shopClassfiy{{ shop.shopId }}">{{ shop.shopClassfiy }}</td>#}
{#                                      <td name="shopImgUrl{{ shop.shopId }}">{{ shop.shopImgUrl }}</td>#}
{#                                      <td>#}
{#                                          <a onclick="getShopData(1, 16, 'del', 0)">删除</a>&nbsp;&nbsp;#}
{#                                          <a id="xg" onclick="submitModifyShop({{ shop.shopId }})">修改</a>&nbsp;&nbsp;#}
{#                                          <a id="wc" onclick="submitModifyShops({{ shop.shopId }})">完成</a>#}
{#                                      </td>#}
{#                                  </tr>#}
{#                              {% endfor %}#}

                            </tbody>
                        </table>

                    {#   第二块结尾                 #}
					</div>
				</div>
			</div>
		</div>
	</div>
</div>

</body>
</html>

manage.py启动文件:

#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys

def main():
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_django_project.settings')
    try:
        from django.core.management import execute_from_command_line
    except ImportError as exc:
        raise ImportError(
            "Couldn't import Django. Are you sure it's installed and "
            "available on your PYTHONPATH environment variable? Did you "
            "forget to activate a virtual environment?"
        ) from exc
    execute_from_command_line(sys.argv)


if __name__ == '__main__':
    main()

至此,是本项目文件的全部内容,如下图是:
在这里插入图片描述
下篇文章见!!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值