django上傳並顯示圖片

環境

python 3.5
django 1.10.6html

步驟

  1. 建立名爲 testupload的項目
django-admin startproject testupload
  1. 在項目testupload中建立名爲uploadpic的app
cd testupload
python manage.py startapp uploadpic
  1. 把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',
)
  1. 在文件夾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')
  1. 在數據庫裏生成django一些元數據表.執行下面命令.
python manage.py migrate
  1. 生成模塊.執行下面命令.
python manage.py makemigrations uploadpic
  1. 再在數據庫裏生成IMG的數據表.執行下面命令
python manage.py migrate
  1. 在文件夾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)
  1. 在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)
  1. 編輯testupload文件夾下的setting.py文件,添加以下代碼:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')
  1. 在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>
  1. 在upload.html同目錄下建立show.html文件,內容以下:
<img src='{{ aaa.img.url }}' />
  1. 運行django程序
python manage.py runserver

打開瀏覽器,輸入localhost:8000/upload,進入圖片上傳頁面,上傳後會顯示圖片.python

參考資料

  1. Django上傳並顯示圖片, 2016
  2. Django官方文檔
相關文章
相關標籤/搜索