環境
python 3.5
django 1.10.6
步驟
- 創建名為 testupload的項目
django-admin startproject testupload
- 在項目testupload中創建名為uploadpic的app
cd testupload
python manage.py startapp uploadpic
- 把uploadpic加入到settings.py中的INSTALLED_APPS中
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'uploadpic',
)
- 在文件夾uploadpic下,編輯models.py,創建IMG類.創建這個類是為了使用django的ImageField,使上傳不用直接操作文件,簡化上傳的代碼邏輯.
from __future__ import unicode_literals
from django.db import models
class IMG(models.Model):
img = models.ImageField(upload_to='upload')
- 在數據庫里生成django一些元數據表.執行下面命令.
python manage.py migrate
- 生成模塊.執行下面命令.
python manage.py makemigrations uploadpic
- 再在數據庫里生成IMG的數據表.執行下面命令
python manage.py migrate
- 在文件夾uploadpic下,編輯views.py,創建圖片上傳與顯示函數.
from django.shortcuts import render
from uploadpic.models import IMG
def upload(request):
return render(request, 'uploadpic/upload.html')
def show(request):
new_img = IMG(img=request.FILES.get('img'))
new_img.save()
content = {
'aaa': new_img,
}
return render(request, 'uploadpic/show.html', content)
- 在testupload文件夾下,編輯urls.py文件
from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from showpic.views import show
from showpic.views import upload
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^upload', upload),
url(r'^show', show),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
- 編輯testupload文件夾下的setting.py文件,添加如下代碼:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
- 在uploadpic文件夾下創建templates文件夾,再在templates文件夾下創建uploadpic文件夾,再在新創建的uploadpic文件夾下創建upload.html文件,內容如下:
<form method="POST" enctype="multipart/form-data"
action="./../show">
{% csrf_token %}
<input type="file" name="img">
<button type="submit">上傳</button>
</form>
- 在upload.html同目錄下創建show.html文件,內容如下:
<img src='{{ aaa.img.url }}' />
- 運行django程序
python manage.py runserver
打開瀏覽器,輸入localhost:8000/upload,進入圖片上傳頁面,上傳后會顯示圖片.
參考資料
- Django上傳並顯示圖片, 2016
- Django官方文檔