zoukankan      html  css  js  c++  java
  • 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官方文档
  • 相关阅读:
    四川省选2012 day1 喵星球上的点名 (后缀数组,并不是完全的正解)
    6.2.1 最短路
    5.3.3 敌兵布阵
    6.1.1 Constructing Roads
    6.2.4 Arbitrage
    6.1.6 Jungle Roads
    5.3.6 Cow Sorting (HDU 及 POJ)
    6.2.5 Trucking
    6.1.4 还是畅通工程
    6.1.3 畅通工程
  • 原文地址:https://www.cnblogs.com/zhouyang209117/p/6497913.html
Copyright © 2011-2022 走看看