一、Django使用云存储
-
建立项目
django-admin startproject project_demo
-
创建子应用
python manage.py startapp app_name
-
修改配置文件,设置模板视图路径
settings.py
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', ], }, }, ]
-
建立逻辑视图
from django.shortcuts import render from .models import Upload # Create your views here. def upload_file(request): if request.method == 'GET': return render(request,'upload.html') # 上传文件 elif request.method == 'POST': # 获取上传的文件,如果没有文件,则默认为None file = request.FILES.get('file') return render(request,'show.html',{'upload':upload}) def get_file(request,pk): # 获取文件 upload = Upload.objects.get(pk=pk) return render(request,'show.html',{'upload':upload})
-
建立路由地址
from django.urls import path from . import views urlpatterns = [ path('upload_file/', views.upload_file, name='upload_file'), path('get_file/<int:pk>/', views.get_file, name='get_file'), ]
-
建立模板页面
upload.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h2>这个测试</h2> <form action="/upload_file/" method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="img"><br> <input type="text" name="desc"><br> <input type="submit" value="上传"> </form> </body> </html>
show.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<ul>
<li>图片名:{{img.name}}</li>
<li>图片地址:{{img.url}}</li>
<li><img src="{{img.url}}" alt=""></li>
</ul>
</body>
</html>