一、从数据库读取数据,在views.py中写入代码,如:
from django.http importJsonResponsefrom apps.market.models importUser#Create your views here.
#从数据库获取用户数据
defget_Users(request):try:#使用ORM获取所有用户信息 并把对象转为字典格式
obj_users =User.objects.all().values()#把外层的容器转为List
users =list(obj_users)#返回
return JsonResponse({'code': 1, 'data': users})exceptException as e:#如果出现异常,返回
return JsonResponse({'code': 0, 'msg': "获取用户信息出现异常,具体错误:" + str(e)})
二、在urls.py中添加代码,以便前端能够访问到数据,如:
urlpatterns =[
path('admin/', admin.site.urls),
path('goods/', views.get_Goods),//添加该行代码
]
三、在setting.py的ALLOWED_HOSTS中添加本机ip,如:
ALLOWED_HOSTS = ['192.168.182.128']
四、在前端的js文件中添加使用axios请求后端数据的函数,如:
//获取所有物品信息
getGoods: function() {//使用axios实现ajax请求
let that = thisaxios
.get(that.baseURL+ 'goods/')
.then(function(res) {//请求成功后执行的函数
if (res.data.code === 1)
{
that.goods=res.data.datafor(g of that.goods)
{
g.image= that.baseURL+'media/'+g.image
}
that.goodsTotal=res.data.data.length
that.displayGoods=that.goods
}else
//失败的提示!
that.$message.error(res.data.msg)
}
)
.catch(function(err) {//请求失败后执行的函数
console.log(err)
}
)
},
五、解决axios的跨域请求问题,在终端输入pip install django-cors-headers,然后在setting.py的INSTALLED_APPS中添加corsheaders,接着在setting.py的MIDDLEWARE中添加corsheaders.middleware.CorsMiddleware。最后在setting.py中添加代码:
#添加Cors配置#1. 设置白名单,凡是出现在白名单的域名都可以访问后端
CORS_ORIGIN_WHITELIST = ('http://127.0.0.1:8080',)#2. 是指Cors Cookie
CORS_ALLOW_CREDENTIALS = True
六、前端向后端发送数据,如搜索信息:
queryGoods:function() {//搜索物品
let that = this
//开始Ajax请求
axios
.post(
that.baseURL+ "query/",
{
inputstr: that.inputStr,
item: that.selectItem,
}
)
.then(function(res) {if (res.data.code === 1) {//把数据给displaygoods
that.displayGoods =res.data.data;
console.log(res.data.data.length)//提示:
that.$message({
message:'查询数据加载成功!',
type:'success'});
}else{//失败的提示!
that.$message.error(res.data.msg);
}
})
.catch(function(err) {
console.log(err);
that.$message.error("获取后端查询结果出现异常!");
});
}
七、前端访问后端图片,
1)现在后端根目录创建media文件夹;
2)将图片储存在media中;
3)在setting.py中添加代码
#设置上传文件的目录和外部访问的路径
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL= '/media/'
4)在url.py中添加代码:
from django.conf.urls.static import static
#添加这行--- 允许所有的media文件被访问
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
如访问图片sadf54sad1as.jpg: