django上传并显示图片

环境

python 3.5
django 1.10.6

步骤

  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,进入图片上传页面,上传后会显示图片.

参考资料

  1. Django上传并显示图片, 2016
  2. Django官方文档
原文地址:https://www.cnblogs.com/zhouyang209117/p/6497913.html