Django的配置:
pycharm中创建django工程之后注释掉MIDDLEWARE项中的‘django.middleware.csrf.CsrfViewMiddleware‘。此处作用是为了能够让js获取到cookie值
同时为了使用mysql,我们在setting中修改DATABASES中的‘default‘项为
‘ENGINE‘: ‘django.db.backends.mysql‘, ‘NAME‘: ‘db_test_shop1‘, ‘HOST‘:‘127.0.0.1‘, ‘PORT‘:3306, ‘USER‘:‘root‘, ‘PASSWORD‘:‘1415926‘,
参数一目了然无需多讲
在django的控制台下执行python manage.py startapp 你的app项目名来新建一个app项目,此后的工程都在这里写。然后在setting中的INSTALLED_APPS项中注册app,添加‘django.apps.你的app的名字Config‘
同时在setting中添加以下代码来寻找static路径和模板代码路径
STATICFILES_DIRS=[ os.path.join(BASE_DIR,‘static‘) ]
开启调试功能的代码为在setting中添加
LOGGING = { ‘version‘: 1, ‘disable_existing_loggers‘: False, ‘handlers‘: { ‘console‘:{ ‘level‘:‘DEBUG‘, ‘class‘:‘logging.StreamHandler‘, }, }, ‘loggers‘: { ‘django.db.backends‘: { ‘handlers‘: [‘console‘], ‘propagate‘: True, ‘level‘:‘DEBUG‘, }, } }
为了使用现成的数据库中的数据,我们可以通过在控制台中执行python manage.py inspectdb来获取代码,复制粘贴到app中的model文件中
html模板中若为了使用django的模板语言需要在开头加上{% load static %}
Django中后端的编写
以上准备工作完成之后在app项目文件夹里的urls里如下配置
from django.contrib import admin from django.urls import path from tableapp.views import * urlpatterns = [ path(‘admin/‘, admin.site.urls), path(‘‘,indexRender_CookieAndSession), path(‘test‘,testAjax_CookieAndSession), path(‘goTestRender‘,goTestRender), path(‘getSession‘,getSession), ]
path的第一个参数为前端的请求地址,第二个参数为调用的函数
然后就在view文件里编写函数即可
from django.shortcuts import render from tableapp.models import * from django.views.static import HttpResponse from django.http import JsonResponse from tableapp.models import * import json from django.views.decorators.csrf import csrf_exempt # Create your views here. def getSession(request): return JsonResponse({"result":request.session.get(json.loads(request.body).get("key"))}) def indexRender_CookieAndSession(request): #测试session request.session["t1_session"]="session1" #删除session: del request.session["t1_session"] #网页转发到index.html rsp = render(request,"index.html") #测试cookie设置 rsp.set_cookie("t1_cookie",233) #删除cookie: rsp.delete_cookie("t1_cookie") return rsp def goTestRender(request): return render(request,"test.html") # @csrf_exempt def testAjax_CookieAndSession(request): #request是json格式传过来的参数,需要转换成字典对象 params = json.loads(request.body) print("testParamInteger:",params["testParamInteger"]) print("testParamString:", params["testParamString"]) # 测试session request.session["t2_session"] = "session2" #orm简单的两表查询 # 用模型类.objects来进行数据库操作,filter等同于where操作,values_list将查询结果转换成结果元祖,而非values的字典对组成的json对象形式。可以通过切片进行选取操作,[开始位置:结束位置:隔几个取一个](以上参数和切片一样可以任意省略) data = TGoods.objects.filter(goods_status=1).values_list("goods_id","goods_name","goods_price","type__t_g_type__type_name")[0:10:1] title = ("商品ID","商品名","商品价格","商品类别","操作") result = {"result":1,"data":data,"title":title} #这里可以替换成 return JsonResponse(result) resp = HttpResponse(json.dumps(result),content_type="application/json") resp.set_cookie("t2_cookie","cookie2") return resp
然后提前放上测试用的各种代码
<!DOCTYPE html> <html lang="en"> <head> {% load static %} <meta charset="UTF-8"> <script type="text/javascript" src="{% static ‘js/jquery-3.2.1.min.js‘ %}"></script> <script type="text/javascript" src="{% static ‘js/jquery-cookie.js‘ %}"></script> <script type="text/javascript" src="{% static ‘js/my-session.js‘ %}"></script> <title>Title</title> </head> <body> <a href="goTestRender">跳转到test页面</a> </body> <script type="text/javascript"> console.log("render cookie:",$.cookie("t1_cookie")) console.log("render session:",getSession("t1_session")) </script> </html>
index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> {% load static %} <title>test table</title> {# <link rel="stylesheet" href="style.css">#} <!-- Delete ".min" for console warnings in development --> </head> <body> <!-- 取消这个范围内的django解析,从而解决django与vue语法冲突问题 --> {% verbatim %} <script type="text/x-template" id="my_test_template"> <table> <thead> <tr> <td v-for="t in title"> {{ t }} </td> </tr> </thead> <tbody> <tr v-for="row in testData"> <td v-for="d in row">{{ d }}</td> </tr> </tbody> </table> </script> {% endverbatim %} <!-- Vue.compent里的变量名=实例化时对应的变量名 --> <!-- Vue.compent里的变量名如果是驼峰命名两个单词的话需要用中划线分割 --> <my-test-table :title="myTitle" :test-data="myData" ></my-test-table> </body> <script type="text/javascript" src="{% static ‘js/jquery-3.2.1.min.js‘ %}"></script> <script type="text/javascript" src="{% static ‘js/jquery-cookie.js‘ %}"></script> <script type="text/javascript" src="{% static ‘js/my-session.js‘ %}"></script> <script type="text/javascript" src="{% static ‘js/vue.js‘ %}"></script> <script type="text/javascript" src="{% static ‘js/table.js‘ %}"></script> </html>
test.html
function getSession(key) { result = undefined $.ajax({ url:"getSession", type:"post", dataType:"json", data:JSON.stringify({key:key}), async:false, success:function (data) { result = data.result } }) return result }
my-session.js
Vue.component(‘my-test-table‘,{ template:"#my_test_template", props:{ title:Array, testData:Array, } }) function getData() { $.ajax({ url:"test", type:"post", dataType:"json", data:JSON.stringify({ testParamInteger:1, testParamString:"测试参数" }), success:function (data) { console.log(data) // 传过来的参数自动被解析成对象了,无需转换 var myVue = new Vue({ el:"my-test-table", data:{ myTitle:data.title, myData:data.data } }) // 测试cookie和session console.log("Ajax Cookie:"+$.cookie("t2_cookie")) console.log("Ajax Session:"+getSession("t2_session")) } }) } $(function () { getData() })
table.js
测试结果
难点解释:
前端的my-session.js中的async:flase是为了取消异步,能让返回值在获取到结果之后再返回
cookie获取方法为引入jquery-cookie.js文件,调用$.cookie即可
session的获取方法为my-session中再次请求
此外其他点都在注释里了
原文地址:https://www.cnblogs.com/dofstar/p/11711502.html