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

文件层级目录
  • djiangoproject
    • djiangoproject

      • settings.py
      • urls.py
      • wsgi.py
    • shopapp

      • entity
      • dao
      • service
      • admin.py
      • apps.py
      • models.py
      • test.py
      • views.py
    • static

      • css
      • bootstrap
      • js
      • uploads
      • echarts
    • templates

      • jobinfo
      • personalinfo
      • systeminfo
      • footer.html
      • index.html
      • left.html
      • login.html
      • main.html
      • top.html
    • manage.py


settings.py

"""
Django settings for djangoproject project.

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

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 = '(46xri8ef295s*edox_(t=w%k$ks=wx0wmm=3@1yo!c=je81-p'

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 = 'djangoproject.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 = 'djangoproject.wsgi.application'


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

DATABASES = {
   
    'default': {
   
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db_test_shop1',
        'HOST': '127.0.0.1',
        'USER': 'root',
        'PASSWORD':'root',
        'PORT': '3306',
        '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"),
)

# 配置输出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

"""djangoproject URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.2/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
from shopapp.views import *

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index),
    path('gologin/', goLogin),
    path('login/', login),
    path('logout/', logout),
    path('regist.do/', regist),
    path('upload.do/', uploadFile),
    path('goajaxjobtaskinfo/', goJobTaskInfo),
    path('ajaxjobtaskinfo/', getJobTaskInfo),
    path('ajaxjobsalary/', getJobSalary),
    path('goajaxuserinfo/', goAjaxUserInfo),
    path('ajaxuserinfo/', getUserInfo),
    path('ajaxdeptinfo/', getDeptList)
]

wsgi.py

"""
WSGI config for djangoproject project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoproject.settings')

application = get_wsgi_application()

dao层(自配的数据库连接与操作,该项目未用)


entity下
jobtask.py

# 封装数据类 VO:value object  entity 类
class JobTask():
    def __init__(self):
        self.__taskId = None
        self.__taskTitle = None
        self.__taskURL = None
        self.__taskState = None
        pass

    @property
    def taskId(self):
        return self.__taskId
        pass

    @taskId.setter
    def taskId(self, taskId):
        self.__taskId = taskId
        pass

    @property
    def taskTitle(self):
        return self.__taskTitle
        pass

    @taskTitle.setter
    def taskTitle(self, taskTitle):
        self.__taskTitle = taskTitle
        pass

    @property
    def taskURL(self):
        return self.__taskURL
        pass

    @taskURL.setter
    def taskURL(self, taskURL):
        self.__taskURL = taskURL
        pass

    @property
    def taskState(self):
        return self.__taskState
        pass

    @taskState.setter
    def taskState(self, taskState):
        self.__taskState = taskState
        pass
    pass

entity下
user.py

# 封装数据类 VO:value object  entity 类
class User():
    def __init__(self):
        self.__userId = None
        self.__userName = None
        self.__userPwd = None
        self.__userSex = None
        self.__userPic = None
        self.__userBirth = None
        self.__userIntro = None
        self.__userDeptId = None
        self.__userDeptName = None
        self.__userRole = None
        pass

    @property
    def userId(self):
        return self.__userId
        pass

    @userId.setter
    def userId(self, userId):
        self.__userId = userId
        pass

    @property
    def userName(self):
        return self.__userName
        pass

    @userName.setter
    def userName(self, userName):
        self.__userName = userName
        pass

    @property
    def userPwd(self):
        return self.__userPwd
        pass

    @userPwd.setter
    def userPwd(self, userPwd):
        self.__userPwd = userPwd
        pass

    @property
    def userSex(self):
        return self.__userSex
        pass

    @userSex.setter
    def userSex(self, userSex):
        self.__userSex = userSex
        pass

    @property
    def userPic(self):
        return self.__userPic
        pass

    @userPic.setter
    def userPic(self, userPic):
        self.__userPic = userPic
        pass

    @property
    def userBirth(self):
        return self.__userBirth
        pass

    @userBirth.setter
    def userBirth(self, userBirth):
        self.__userBirth = userBirth
        pass

    @property
    def userIntro(self):
        return self.__userIntro
        pass

    @userIntro.setter
    def userIntro(self, userIntro):
        self.__userIntro = userIntro
        pass

    @property
    def userDeptId(self):
        return self.__userDeptId
        pass

    @userDeptId.setter
    def userDeptId(self, userDeptId):
        self.__userDeptId = userDeptId
        pass

    @property
    def userDeptName(self):
        return self.__userDeptName
        pass

    @userDeptName.setter
    def userDeptName(self, userDeptName):
        self.__userDeptName = userDeptName
        pass

    @property
    def userRole(self):
        return self.__userRole
        pass

    @userRole.setter
    def userRole(self, userRole):
        self.__userRole = userRole
        pass
    pass

migrations(无文件)
service(未使用)


admin.py

from django.contrib import admin

# Register your models here.
from shopapp.models import TUser
from shopapp.models import JobDept
admin.site.register(TUser)
admin.site.register(JobDept)

apps.py

from django.apps import AppConfig


class ShopappConfig(AppConfig):
    name = 'shopapp'

models.py

# This is an auto-generated Django model module.
# You'll have to do the following manually to clean this up:
#   * Rearrange models' order
#   * Make sure each model has one field with primary_key=True
#   * Make sure each ForeignKey has `on_delete` set to the desired behavior.
#   * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table
# Feel free to rename the models, but don't rename db_table values or field names.
from django.db import models

class JobDept(models.Model):
    dept_id = models.IntegerField(primary_key=True)
    dept_name = models.CharField(unique=True, max_length=45, blank=True, null=True)
    dept_parentid = models.IntegerField(blank=True, null=True)

    class Meta:
        managed = False
        db_table = 'job_dept'

class TUser(models.Model):
    user_id = models.AutoField(db_column='USER_ID', primary_key=True)  # Field name made lowercase.
    user_name = models.CharField(db_column='USER_NAME', unique=True, max_length=32)  # Field name made lowercase.
    user_pwd = models.CharField(db_column='USER_PWD', max_length=512)  # Field name made lowercase.
    user_age = models.IntegerField(db_column='USER_AGE', blank=True, null=True)  # Field name made lowercase.
    user_sex = models.IntegerField(db_column='USER_SEX', blank=True, null=True)  # Field name made lowercase.
    user_qq = models.IntegerField(db_column='USER_QQ', blank=True, null=True)  # Field name made lowercase.
    user_cellphone = models.CharField(db_column='USER_CELLPHONE', max_length=20, blank=True, null=True)  # Field name made lowercase.
    user_money = models.FloatField(db_column='USER_MONEY', blank=True, null=True)  # Field name made lowercase.
    user_status = models.IntegerField(db_column='USER_STATUS', blank=True, null=True)  # Field name made lowercase.
    user_pic = models.CharField(db_column='USER_PIC', max_length=128, blank=True, null=True)  # Field name made lowercase.
    user_role = models.IntegerField(db_column='USER_ROLE', blank=True, null=True)  # Field name made lowercase.

    jobDept= models.ForeignKey(JobDept, db_column='', on_delete=models.CASCADE, blank=True, null=True, to_field='dept_id')  # null=True生成left join
    user_birth = models.DateTimeField(db_column='USER_BIRTH', blank=True, null=True)  # Field name made lowercase.
    user_intro = models.TextField(db_column='USER_INTRO', blank=True, null=True)  # Field name made lowercase.

    class Meta:
        managed = False
        db_table = 't_user'





tests.py
(无代码)


views.py

from django.shortcuts import render,redirect
from django.http.response import HttpResponse
from shopapp.service.userservice import UserService
from shopapp.service.jobtaskservice import JobTaskService
from shopapp.entity.jobtask import JobTask
import json
import hashlib
from .models import TUser
from .models import JobDept
from django.core import serializers
import os
from datetime import datetime

# Create your views here.
userService = UserService()
jobTaskService = JobTaskService()

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

def goLogin(request):
    return render(request, 'login.html')
    pass

def login(request):
    userName = request.POST.get('userName')
    userPwd = request.POST.get('userPwd')
    remeberMe = request.POST.get('rememberMe')

    result = userService.findUserByUserName(userName)
    isLogin = False
    if result and (remeberMe == None or remeberMe == 'false'):
        if result[0][2] == hashlib.md5(userPwd.encode(encoding='utf-8')).hexdigest():
            isLogin = True
            pass
    elif result and remeberMe == 'true':
        if result[0][2] == userPwd:
            isLogin = True
            pass
        pass

    if isLogin:
        userItem = {
   }
        userItem['userId'] = result[0][0]
        userItem['userName'] = result[0][1]
        userItem['userPic'] = result[0][9]
        userItem['userRole'] = result[0][10]
        request.session['user'] = userItem
        response = render(request, 'main.html')
        if remeberMe == 'false':
            response.set_cookie('userName', userName)
            response.set_cookie('userPwd', result[0][2])
            response.set_cookie('rememberMe', 'true')
            pass
        elif remeberMe == None:
            response = render(request, 'main.html')
            response.delete_cookie('userName')
            response.delete_cookie('userPwd')
            response.delete_cookie('rememberMe')
            pass

        return response
    else:
        return render(request, 'login.html')
    pass

def regist(request):
    userDict = json.loads(request.body.decode('utf-8'))
    '''
    user = TUser()
    user.user_name = userDict.get('userName')  # 表单提交的数据使用request.form[]
    user.user_pwd = hashlib.md5((userDict.get('userPwd')).encode(encoding='utf-8')).hexdigest()
    user.user_pic = userDict.get('userPic')
    user.user_birth = datetime.strptime(userDict.get('userBirth'), '%Y-%m-%d')
    user.user_sex = userDict.get('userSex')
    user.user_intro = userDict.get('userIntro')
    result = user.save()
    '''
    result = TUser.objects.create(
        user_name = userDict.get('userName'),
        user_pwd=hashlib.md5((userDict.get('userPwd')).encode(encoding='utf-8')).hexdigest(),
        user_pic=userDict.get('userPic'),
        user_birth=datetime.strptime(userDict.get('userBirth'), '%Y-%m-%d'),
        user_sex=userDict.get('userSex'),
        user_intro=userDict.get('userIntro')
    )
    if result:
        result = 1
    else:
        result = 0
    return HttpResponse(json.dumps({
   'result': result}), content_type="application/json")
    pass

def logout(request):
    request.session.flush()
    return render(request, 'login.html')
    pass

def goJobTaskInfo(request):
    return render(request, "jobinfo/jobtaskinfo.html")
    pass

def getJobTaskInfo(request):
    jobTaskData = request.body.decode('utf-8')
    jobTaskDict = json.loads(jobTaskData)
    tData = {
   }

    jobTask = JobTask()
    jobTask.taskTitle = jobTaskDict.get('taskTitle')
    jobTask.taskURL = jobTaskDict.get('taskURL')

    currentPage = int(jobTaskDict.get('currentPage'))
    pageSize = int(jobTaskDict.get('pageSize'))
    opr = jobTaskDict.get('opr')
    taskId = int(jobTaskDict.get('taskId'))
    jobTask.taskId = taskId

    updateResult = 0
    if opr == 'del':
        updateResult = jobTaskService.removeJobTask(taskId)
        pass
    elif opr == 'update':
        tTask = jobTaskService.findJobTaskByJobTaskId(taskId)
        tData['taskId'] = tTask.taskId
        tData['taskTitle'] = tTask.taskTitle
        tData['taskURL'] = tTask.taskURL
        returnData = {
   'code': 1, 'jobTaskData': tData, 'pageSize': pageSize, 'currentPage': currentPage, 'opr':'update'}

        return HttpResponse(json.dumps(returnData), content_type="application/json")
    elif opr == 'submitUpdate':
        updateResult = jobTaskService.updateJobTask(jobTask)
        pass

    result = jobTaskService.findPageJobTaskList(jobTask, pageSize, currentPage)
    counts = jobTaskService.countJobTasks(jobTask)
    totalPage = 0

    if(counts%pageSize == 0):
        totalPage = counts//pageSize
    else:
        totalPage = counts // pageSize + 1
        pass

    returnData = {
   'code':1, 'jobTaskData':result, 'pageSize':pageSize, 'currentPage':currentPage, 'totalPage':totalPage, 'updateResult':updateResult, 'opr':'search','counts':counts}

    return HttpResponse(json.dumps(returnData), content_type="application/json")
    pass

def getJobSalary(request):
    result = jobTaskService.findJobMeanSalary()
    returnData = {
   'code':1, 'salary':result}
    r = json.dumps(returnData)
    return HttpResponse(json.dumps(returnData), content_type="application/json")
    pass



def goAjaxUserInfo(request):
    return render(request, "systeminfo/userinfo.html")
    pass

def getUserInfo(request):
    userData = request.body.decode('utf-8')
    userDict = json.loads(userData)
    tData = {
   }

    user = TUser()
    user.user_name = userDict.get('userName')
    user.user_sex = userDict.get('userSex')

    currentPage = int(userDict.get('currentPage'))
    pageSize = int(userDict.get('pageSize'))
    opr = userDict.get('opr')
    userId = int(userDict.get('userId'))
    user.user_id= userId
    user.jobDept_id = int(userDict.get('userDeptId'))

    updateResult = 0
    if opr == 'del':
        updateResult = user.delete()
        pass
    elif opr == 'update':
        tUser = TUser.objects.filter(user_id=userId).values('user_id', 'user_name', 'user_sex', 'jobDept_id', 'jobDept__dept_name')
        tData['userId'] = tUser[0].get('user_id')
        tData['userName'] = tUser[0].get('user_name')
        tData['userSex'] = tUser[0].get('user_sex')
        tData['userDeptId'] = tUser[0].get('jobDept_id')
        tData['userDeptName'] = tUser[0].get('jobDept__dept_name')
        returnData = {
   'code': 1, 'userData': tData, 'pageSize': pageSize, 'currentPage': currentPage, 'opr':'update'}

        return HttpResponse(json.dumps(returnData), content_type="application/json")
    elif opr == 'submitUpdate':
        currentPage = 1
        updateResult = TUser.objects.filter(user_id=userId).update(user_sex=user.user_sex, jobDept_id=user.jobDept_id)
        pass
    query = TUser.objects
    if user.user_name:
        query = query.filter(user_name__contains=user.user_name)
    if user.user_sex:
        query = query.filter(user_sex=user.user_sex)
        pass

    startRow =  (currentPage - 1)*pageSize
    endRow  = currentPage*pageSize
    result = query.values('user_id', 'user_name', 'user_sex', 'jobDept__dept_name')[startRow:endRow]  # 会生成 LIMIT 2 OFFSET 1

    counts = query.count()

    totalPage = 0
    if(counts%pageSize == 0):
        totalPage = counts//pageSize
    else:
        totalPage = counts // pageSize + 1
        pass

    # data = serializers.serialize("json", result, use_natural_foreign_keys=True)
    # data = json.loads(data)
    data = []
    for tempUser in result:
        dictItem = {
   'pk':tempUser.get('user_id')}
        fieldsItem ={
   'user_name':tempUser.get('user_name'), 'user_sex':tempUser.get('user_sex'), 'user_deptname':tempUser.get('jobDept__dept_name')}
        dictItem['fields'] = fieldsItem
        data.append(dictItem)
        pass
    '''
    for tempUser, tdata in zip(result, data):
        tdata['fields']['user_deptname'] = tempUser.jobDept.dept_name # 获取外键关联的时候,是第二次查询
        pass
    '''
    returnData = {
   'code':1, 'userData':data, 'pageSize':pageSize, 'currentPage':currentPage, 'totalPage':totalPage, 'updateResult':updateResult, 'opr':'search','counts':counts}

    return HttpResponse(json.dumps(returnData), content_type="application/json")
    pass

def getDeptList(request):
    parentId = int(request.GET.get('parentId'))
    if parentId ==0:
        result = JobDept.objects.filter(dept_parentid__isnull=True).all()
    else:
        result = JobDept.objects.filter(dept_parentid=parentId).all()
    data = serializers.serialize("json", result)
    data = json.loads(data)

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

def uploadFile(request):
    # 后缀需要检查的
    file = request.FILES.get('upload')
    if file:
        try:
            with open(os.path.dirname(__file__) + os.sep + '..' + os.sep + 'static' + os.sep + 'uploads'+ os.sep + file.name, "wb+") as fp:
                for chunk in file.chunks():
                    fp.write(chunk)
                    pass
        except Exception as e:
            return HttpResponse(json.dumps({
   'uploaded': 0, 'fileName': "", 'url': ""}), content_type="application/json")
            pass
        return  HttpResponse(json.dumps({
   'uploaded': 1, 'fileName':file.name, 'url': os.sep + 'static' + os.sep + 'uploads'+ os.sep + file.name}), content_type="application/json")
    else:
        return  HttpResponse(json.dumps({
   'uploaded': 0, 'fileName': "", 'url': ""}), content_type="application/json")
    pass

jobtask.js

function getJobTaskData(currentPage, pageSize, opr, taskId) {
   

    var taskTitle =  document.searchForm.taskTitle.value
    var taskURL = document.searchForm.taskURL.value

    if(opr == 'del'){
   
        if(!confirm('确定要删除吗?')){
   
            return false
        }
    }else if(opr == 'submitUpdate'){
   
        taskTitle = document.taskForm.taskTitle.value
        taskURL = document.taskForm.taskURL.value
        taskId = document.taskForm.taskId.value
        currentPage = document.taskForm.currentPage.value
        pageSize = document.taskForm.pageSize.value
        $('#modal-default').modal('hide')
    }

    $.ajax({
   
        type: 'post',                            // 传数据的方式
        url: '/ajaxjobtaskinfo/',
        dataType: 'json',                        // xml、json、script、html
        data:JSON.stringify({
   
            'taskTitle': taskTitle,     //  $('#taskTitle') == document.getElementById('taskTitle')
            'taskURL' : taskURL,
            'taskId': taskId,
            'pageSize': pageSize,
            'currentPage': currentPage,
            'opr': opr
        }),
        error: function(xhr, err){
   
            alert('请求失败,请检查,' + err + '!')
        },
        success: function(data, textStatus){
       // success对应的回调函数的第一个参数,是服务器返回的数据
            // 查询后、删除后、修改后都走这个if
            if(data.code == 1 && opr != 'update'){
   
                var htmlText = ""
                for(var i =0;i <data.jobTaskData.length;i++){
   
                    htmlText += '<tr>' +
                        '            <td align="center"><input type="checkbox" name="taskId" value="'+  data.jobTaskData[i][0] +'" /></td>\n' +
                        '            <td>' + data.jobTaskData[i][0] + '</td>\n' +
                        '            <td>' + data.jobTaskData[i][1] + '</td>\n' +
                        '            <td style="width: 500px;word-break: break-all;">' + data.jobTaskData[i][2] + '</td>\n' +
                        '            <td style="width: 160px;">\n' +
                        ' <button type="button" class="btn btn-danger" οnclick="getJobTaskData('+ data.currentPage +',' + data.pageSize + ','+ '\'del\''+',' + data.jobTaskData[i][0] +')">删除</button>' +
                        ' <button type="button" class="btn btn-info" οnclick="getJobTaskData('+ data.currentPage +',' + data.pageSize + ','+ '\'update\''+',' + data.jobTaskData[i][0] +')">修改</button>'+
                        '            </td>\n' +
                        '        </tr>\n'
                }
                pageText = '<tr style="text-align: right;"><td colspan="5">'+ '当前第' + data.currentPage + '页&nbsp;&nbsp;总共有' + data.totalPage + '页&nbsp;&nbsp;';
                if(data.currentPage <= 1) {
   
                    pageText += '首页 &nbsp;&nbsp;上一页&nbsp;&nbsp;';
                }else{
   
                     pageText += '<a href="javascript:getJobTaskData(1,10,\'search\', 0);">首页</a> &nbsp;&nbsp;' +
                        '<a href="javascript:getJobTaskData(' + (data.currentPage - 1) + ', 10, \'search\', 0);">上一页</a>&nbsp;&nbsp;';
                }

                if(data.currentPage >= data.totalPage){
   
                     pageText += '下一页&nbsp;&nbsp;尾页&nbsp;&nbsp;';
                }else {
   
                    pageText += '<a href="javascript:getJobTaskData(' + (data.currentPage + 1) + ', 10, \'search\', 0);">下一页</a>&nbsp;&nbsp;' +
                    '<a href="javascript:getJobTaskData(' + data.totalPage + ', 10, \'search\', 0);">尾页</a>&nbsp;&nbsp;';
                }
                pageText +='总共有'+ data.counts + '条&nbsp;&nbsp;</td></tr>'
                $('#dataBody').empty()
                $('#dataBody').append(htmlText)
                $('#dataBody').append(pageText)

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

                 if( opr != 'search' && data.updateResult > 0 ) {
   
                     alert("操作成功")
                 }else if(opr != 'search' && data.updateResult <= 0){
   
                     alert("操作失败")
                 }
            }else if(data.code == 1 && opr == 'update'){
   
                document.taskForm.taskTitle.value = data.jobTaskData.taskTitle
                document.taskForm.taskURL.value = data.jobTaskData.taskURL
                document.taskForm.taskId.value = data.jobTaskData.taskId
                document.taskForm.currentPage.value = data.currentPage
                document.taskForm.pageSize.value = data.pageSize
                $('#modal-default').modal()
            }
        }
    });
}
$(document).ready(
    function(){
   
        getJobTaskData(1, 10, 'search', 0)
    }
)

userdata.py

function getUserData(currentPage, pageSize, opr, userId) {
   

    var userName =  document.searchForm.userName.value
    var userSex = document.searchForm.userSex.value
    var userDeptId = 0

    if(opr == 'del'){
   
        if(!confirm('确定要删除吗?')){
   
            return false
        }
    }else if(opr == 'submitUpdate'){
   
        userName = document.userForm.userName.value
        userSex = document.userForm.userSex.value
        userId = document.userForm.userId.value
        userDeptId = document.userForm.userDeptId.value
        currentPage = document.userForm.currentPage.value
        pageSize = document.userForm.pageSize.value
    }

    $.ajax({
   
        type: 'post',                            // 传数据的方式
        url: '/ajaxuserinfo/',
        dataType: 'json',                        // xml、json、script、html
        data:JSON.stringify({
   
            'userName': userName,     //  $('#userName') == document.getElementById('userName')
            'userSex' : userSex,
            'userId': userId,
            'userDeptId': userDeptId,
            'pageSize': pageSize,
            'currentPage': currentPage,
            'opr': opr  // 重用一个ajax请求实现增加删除修改查询 CRUD
        }),
        error: function(xhr, err){
   
            alert('请求失败,请检查,' + err + '!')
        },
        success: function(data, textStatus){
       // success对应的回调函数的第一个参数,是服务器返回的数据
            // data = JSON.parse(data)
            if(data.code == 1 && opr != 'update'){
   
                var htmlText = ""
                for(var i =0;i <data.userData.length;i++){
   
                    htmlText += '<tr>' +
                        '            <td align="center"><input type="checkbox" name="userId" value="'+  data.userData[i].pk +'" /></td>\n' +
                        '            <td>' + data.userData[i].pk + '</td>\n' +
                        '            <td>' + data.userData[i].fields.user_name + '</td>\n' +
                        '            <td>' + (data.userData[i].fields.user_sex == 1?'男':'女') + '</td>\n' +
                           '         <td>' + data.userData[i].fields.user_deptname + '</td>\n' +
                        '            <td style="width: 160px;">\n' +
                        ' <button type="button" class="btn btn-danger" οnclick="getUserData('+ data.currentPage +',' + data.pageSize + ','+ '\'del\''+',' + data.userData[i].pk +')">删除</button>' +
                        ' <button type="button" class="btn btn-info" οnclick="getUserData('+ data.currentPage +',' + data.pageSize + ','+ '\'update\''+',' + data.userData[i].pk +')">修改</button>'+
                        '            </td>\n' +
                        '        </tr>\n'
                }
                pageText = '<tr style="text-align: right;"><td colspan="6">'+ '当前第' + data.currentPage + '页&nbsp;&nbsp;总共有' + data.totalPage + '页&nbsp;&nbsp;';
                if(data.currentPage <= 1) {
   
                    pageText += '首页 &nbsp;&nbsp;上一页&nbsp;&nbsp;';
                }else{
   
                     pageText += '<a href="javascript:getUserData(1,10,\'search\', 0);">首页</a> &nbsp;&nbsp;' +
                        '<a href="javascript:getUserData(' + (data.currentPage - 1) + ', 10, \'search\', 0);">上一页</a>&nbsp;&nbsp;';
                }

                if(data.currentPage >= data.totalPage){
   
                     pageText += '下一页&nbsp;&nbsp;尾页&nbsp;&nbsp;';
                }else {
   
                    pageText += '<a href="javascript:getUserData(' + (data.currentPage + 1) + ', 10, \'search\', 0);">下一页</a>&nbsp;&nbsp;' +
                    '<a href="javascript:getUserData(' + data.totalPage + ', 10, \'search\', 0);">尾页</a>&nbsp;&nbsp;';
                }
                pageText +='总共有'+ data.counts + '条&nbsp;&nbsp;</td></tr>'
                $('#dat
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是一个基于Python+Django+MySQL实现的Web数据库系统的示例代码: 1. 首先,需要安装Django和MySQL依赖库。可以通过以下命令进行安装: ``` pip install Django pip install mysqlclient ``` 2. 创建Django项目和应用,可以通过以下命令进行创建: ``` django-admin startproject myproject cd myproject python manage.py startapp myapp ``` 3. 在Django项目的settings.py中,配置MySQL数据库连接信息: ``` DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'mydatabase', 'USER': 'mydatabaseuser', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '3306', } } ``` 4. 在Django应用的models.py中,定义数据库模型: ``` from django.db import models class User(models.Model): name = models.CharField(max_length=50) email = models.EmailField() age = models.IntegerField() def __str__(self): return self.name ``` 5. 进行数据库迁移,创建User表: ``` python manage.py makemigrations python manage.py migrate ``` 6. 在Django应用的views.py中,编写增删改查的视图函数: ``` from django.shortcuts import render, get_object_or_404, redirect from .models import User from .forms import UserForm def user_list(request): users = User.objects.all() return render(request, 'user_list.html', {'users': users}) def user_detail(request, pk): user = get_object_or_404(User, pk=pk) return render(request, 'user_detail.html', {'user': user}) def user_new(request): if request.method == "POST": form = UserForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.save() return redirect('user_detail', pk=user.pk) else: form = UserForm() return render(request, 'user_edit.html', {'form': form}) def user_edit(request, pk): user = get_object_or_404(User, pk=pk) if request.method == "POST": form = UserForm(request.POST, instance=user) if form.is_valid(): user = form.save(commit=False) user.save() return redirect('user_detail', pk=user.pk) else: form = UserForm(instance=user) return render(request, 'user_edit.html', {'form': form}) def user_delete(request, pk): user = get_object_or_404(User, pk=pk) user.delete() return redirect('user_list') ``` 7. 在Django应用的urls.py中,配置URL路由: ``` from django.urls import path from . import views urlpatterns = [ path('', views.user_list, name='user_list'), path('user/<int:pk>/', views.user_detail, name='user_detail'), path('user/new/', views.user_new, name='user_new'), path('user/<int:pk>/edit/', views.user_edit, name='user_edit'), path('user/<int:pk>/delete/', views.user_delete, name='user_delete'), ] ``` 8. 在Django应用的templates目录下,编写HTML模板文件: user_list.html: ``` {% extends "base.html" %} {% block content %} <h1>Users</h1> <table> <tr> <th>Name</th> <th>Email</th> <th>Age</th> <th>Actions</th> </tr> {% for user in users %} <tr> <td>{{ user.name }}</td> <td>{{ user.email }}</td> <td>{{ user.age }}</td> <td> <a href="{% url 'user_detail' pk=user.pk %}">View</a> <a href="{% url 'user_edit' pk=user.pk %}">Edit</a> <a href="{% url 'user_delete' pk=user.pk %}">Delete</a> </td> </tr> {% endfor %} </table> <a href="{% url 'user_new' %}">Add User</a> {% endblock %} ``` user_detail.html: ``` {% extends "base.html" %} {% block content %} <h1>{{ user.name }}</h1> <p>Email: {{ user.email }}</p> <p>Age: {{ user.age }}</p> <a href="{% url 'user_edit' pk=user.pk %}">Edit</a> <a href="{% url 'user_delete' pk=user.pk %}">Delete</a> {% endblock %} ``` user_edit.html: ``` {% extends "base.html" %} {% block content %} <h1>{{ title }}</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> {% endblock %} ``` base.html: ``` <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> </head> <body> <div> <h1><a href="{% url 'user_list' %}">My Project</a></h1> </div> <div> {% block content %}{% endblock %} </div> </body> </html> ``` 9. 在Django应用的forms.py中,定义表单类: ``` from django import forms from .models import User class UserForm(forms.ModelForm): class Meta: model = User fields = ('name', 'email', 'age',) ``` 10. 运行Django开发服务器,查看效果: ``` python manage.py runserver ``` 以上就是一个基于Python+Django+MySQL实现的Web数据库系统的示例代码。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值