Django 图片上传、存储与显示

参考博客http://www.cognize.me/2016/05/09/djangopichtml

 

开始以前要先安装python图像处理库:
pip install --use-wheel Pillowpython


1、数据库设置


1. 先建立一个app,好比叫img_db。

命令行:python manage.py startapp img_db数据库

2. 将其加入到settings.py文件中的INSTALLED_APPS中

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'img_db',
    'corsheaders',
]

 

3. 在models.py中建立表,图片存储使用的是 models.ImageField

例如:django

class IMG(models.Model):
    img = models.ImageField(upload_to='img')
    name = models.CharField(max_length=20)


这里的upload_to是指定图片存储的文件夹名称,上传文件以后会自动建立session

 

4. 更新数据库

python manage.py makemigrations
python manage.py migrateapp

 

2、修改配置文件setting.py

只须要在最后的静态文件区加上下面两行代码:cors

MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/')     #设置静态文件路径为主目录下的media文件夹
MEDIA_URL = '/media/'                                                 #url映射

3、建立模板


1. 在APP目录下建立文件夹templates  

注意:这是django默认的形式,若是想把模板放在其余路径,得本身从新配置。函数


2. 在templates文件夹下建立文件夹,好比叫img_tem

 

3. 在img_tem下建立模板


uploadimg.htmlpost

<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="img">
<button type="submit">上传</button>
</form>


showimg.htmlurl

{% for img in imgs %}
<img src="{{ img.img.url }}" />
{% endfor %}


这里img是Django的Model里的一个实例对象,使用img.img.url能够获取他的url,并且在settings.py中已经对其作了静态映射

4、建立视图函数 view.py

 

@csrf_exempt
def uploadImg(request):
    if request.method == 'POST':
        new_img = IMG(
            img=request.FILES.get('img'),
            name = request.FILES.get('img').name
        )
        new_img.save()
    return render(request, 'img_tem/uploadimg.html')


首先用get方式访问uploadImg(),而后会跳转到uploadimg.html页面,上传文件时会使用post再次访问uploadImg(),这时就会将图片存储在数据库与media/img_tem中。

@csrf_exempt
def showImg(request):
    imgs = IMG.objects.all()
    content = {
        'imgs':imgs,
    }
    for i in imgs:
        print i.img.url
    return render(request, 'img_tem/showimg.html', content

 

5、url.py配置



from django.conf.urls import url
from django.contrib import admin
import view
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^upload', view.uploadImg),
    url(r'^show', view.showImg),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)  这句话是用来指定和映射静态文件的路径

 

完成以后就能够发布了。

相关文章
相关标签/搜索