赞
踩
Django是利用Python语言从事Web开发的首选框架。
Django在发展过程中,为了达到非常高效率的网站结构搭建,提供给开发人员一个干净的项目结构,让开发人员更多精力集中在功能开发上,而不是技术实现上,所有Django对于常规的MVT处理进行了升级——MVT处理模式。
MVT处理模式:实在MVT处理模式上,升级得到的一种更加符合实际项目开发流程的处理思路,在这种处理模式中,将功能比较单一的控制器Controller部分,封装成了路由,由路由来完成请求的分发操作【路由是通过配置实现的】
M(model)模型层、类以及跟数据库相关的代码;
V(view)视图层
T(templates)模板层
其优点也很多,比如功能完善,要素齐全;强大的数据库访问组件;先进的App设计理念;自助式的管理系统admin以及其debug信息全面和完善的文档等。
djangoproject(项目文件名)
—djangoproject(初始文件夹)
——settings.py(配置文件)
——urls.py(路由文件)
——wsgi.py(WSGI机制)
—shopapp(右击选中Terminal 键入python manage.py startapp shopapp命令行生成该文件,包含如下子文件)
——migrations(不需要操作)
——static(包含js文件和css文件)
———js(js文件)
————jquery-3.2.1.min.js(引入jquery框架)
————shop.js(ajax具体应用)
——admin.py(注册model中的类)
——apps.py(注册app)
——model.py(右击选中Terminal 键入python manage.py inspectdb > shopapp/models.py 自动生成settings.py中配置的数据库中的各个表的数据列)
——tests.py
——views.py(CRUD的具体实现)
—templates(html文件)
——jobtaskinfo.html(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
from django.contrib import admin from django.urls import path from shopapp.views import * urlpatterns = [ path('admin/', admin.site.urls), path('', index), path('gologin.do', 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
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoproject.settings')
application = get_wsgi_application()
shop.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 + '页 总共有' + data.totalPage + '页 '; if(data.currentPage <= 1) { pageText += '首页 上一页 '; }else{ pageText += '<a href="javascript:getJobTaskData(1,10,\'search\', 0);">首页</a> ' + '<a href="javascript:getJobTaskData(' + (data.currentPage - 1) + ', 10, \'search\', 0);">上一页</a> '; } if(data.currentPage >= data.totalPage){ pageText += '下一页 尾页 '; }else { pageText += '<a href="javascript:getJobTaskData(' + (data.currentPage + 1) + ', 10, \'search\', 0);">下一页</a> ' + '<a href="javascript:getJobTaskData(' + data.totalPage + ', 10, \'search\', 0);">尾页</a> '; } pageText +='总共有'+ data.counts + '条 </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) } )
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'
model.py
from django.db import models class JobDept(models.Model): dept_id = models.IntegerField(primary_key=True) dept_name = models.TextField(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, on_delete=models.DO_NOTHING, blank=True, null=True) # jobDept__dept_id/ user_birth = models.DateTimeField(db_column = ' USER_BIRTH', blank = True, null = True) #Field name madelowercase. user_intro = models.DateTimeField(db_column = ' USER_INTRO', blank = True, null = True) class Meta: managed = False db_table = 't_user'
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') rememberMe = request.POST.get('rememberMe') result = userService.findUserByUserName(userName) isLogin = False if result and (rememberMe == None or rememberMe == 'false'): if result[0][2] == hashlib.md5(userPwd.encode(encoding='utf-8')).hexdigest(): isLogin = True elif result and rememberMe == 'false': if result[0][2] == userPwd: isLogin = True result = userService.findUserByUserName(userName) if result and result[0][2] == hashlib.md5(userPwd.encode(encoding='utf-8')).hexdigest(): 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 rememberMe == 'false': response.set_cookie('userName', userName) response.set_cookie('userPwd', result[0][2]) response.set_cookie('rememberMe', 'true') elif rememberMe == 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('userId') # user.user_pwd = hashlib.md5((userDict.get('userPwd')). encode(encoding='utf-8')).hexdigest() # 表单提交的数据使用request.form[] # user.user_pic = userDict.get('userPic') # user.user_birth = datetime.strftime(userDict.get('userBirth'), '%Y-%m-%d') # user.user_sex = userDict.get('userSex') # user.user_intro = userDict.get('userIntro') result = TUser.objects.create( user_name=userDict.get('userId'), 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) #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) # 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: # 将上传文件拆分成多个块(当上传文件大于2.5MB时,自动拆分),使用文件对象.chunks()函数。 for chunk in file.chunks(): fp.write(chunk) 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
jobtaskinfo.html
{% include 'top.html' %} {% include 'left.html' %} {% load static %} <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <h1> 系统管理 <small>任务信息管理</small> </h1> <ol class="breadcrumb"> <li><a href="#"><i class="fa fa-dashboard"></i> 采集管理</a></li> <li><a href="#">系统任务</a></li> <li class="active">任务信息管理</li> </ol> </section> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-xs-12"> <div class="box"> <div class="box-header"> <h3 class="box-title">任务信息</h3> </div> <!-- /.box-header --> <div class="box-body"> <form method="post" name="searchForm" class="form-inline"> <div class="form-group"> <div class="form-group"> <label class="control-label" for="taskTitle">任务名:</label> <input type="text" name="taskTitle" class="form-control" id="taskTitle"/> </div> <div class="form-group"> <label class="control-label" for="taskURL">任务地址: </label> <input type="text" name="taskURL" class="form-control" id="taskURL" /> </div> <input type="hidden" name="currentPage" value="1"/> <input type="hidden" name="pageSize" value="10"/> <button class="btn btn-primary" type="button" οnclick="getJobTaskData(1, 10, 'search', 0)">查询</button> </div> </form> <table class="table table-responsive table-bordered"> <caption>{{ message }}</caption> <thead> <tr> <th style="text-align: center;width: 80px;"> <input type="button" value="全选"/> </th> <th>任务ID</th> <th>任务名称</th> <th style="width: 300px;word-wrap: break-word;overflow: hidden;">任务URL地址</th> <th>操作</th> </tr> </thead> <tbody id="dataBody"> </tbody> </table> <div class="modal fade" id="modal-default"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span></button> <h4 class="modal-title">修改任务信息</h4> </div> <div class="modal-body"> <form method="post" name="taskForm"> 任务名称:<input type="text" name="taskTitle" /> 采集URL地址: <input type="text" name="taskURL" /> <input type="hidden" name="taskId"/> <input type="hidden" name="currentPage" value="1"/> <input type="hidden" name="pageSize" value="10"/> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-default pull-left" data-dismiss="modal">取消</button> <button type="button" class="btn btn-primary" οnclick="getJobTaskData(1, 10, 'submitUpdate', 0)">保存</button> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> </div> <!-- /.box-body --> </div> <!-- /.box --> </div> <!-- /.col --> </div> <!-- /.row --> </section> <!-- /.content --> </div> <!-- /.content-wrapper --> {% include 'footer.html' %} <script type="text/javascript" src="{% static 'js/jobtask.js' %}"></script>
manage.py
import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'djangoproject.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()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。