Django 图片上传到数据库 并调用显示

环境:Django2.0 Python3.6.4html

创建项目,数据库设置,就不说了。python

直接上代码:数据库

在models.py中,须要创建模型,这里使用了ImageField字段,用来存储图片路径,这个字段继承了FileField字段,本质上是同样的。这里Image.Field的默认max_length=100,咱们能够根据需求本身指定。upload_to用于指定上传到哪一个路径下。django

PS: 使用ImageField首先须要装Pillow。app

 1 pip install Pillow 函数

 

1 class Test(models.Model):
2     name = models.CharField(max_length=50)
3     image = models.ImageField(upload_to='logo')
4     def __str__(self):
5         return self.name

创建好模型,须要进行迁移操做,post

1 python manage.py makemigrations  
2 python manage.py migrate 

在settings.py中,设置MEDIA_URL和MEDIA_ROOT编码

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

 咱们须要告诉Django,媒体文件的位置在哪里。这样就和数据库存储的路径相对应了,具体就是MEDIA_ROOT指定目录,upload_to就是在这个目录下进行操做。url


 

1. 显示图片(图片调用) 

  为了可以方便录入数据,咱们使用django后台管理,建立管理页面。spa

python manage.py createsuperuser

   根据提示进行建立。在app下admin.py中将须要上面建立的模型进行添加。

admin.site.register(Test)

   开启runserver,打开admin页面,就能够建立具体的数据了,将图片进行添加。

  咱们须要调用的话,须要在view.py中将数据进行传递。

img = Test.objects.all()
return render(request, 'home.html', {'img':img})

   在视图函数中加入,上面两句。在模板中,将图片展示出来:

{% for i in img %}
<img src="{{ MEDIA_URL }}{{ i.image }}">
{% endfor %}

   这里{{ MEDIA_URL }}是必需要的,由于数据库取出来的地址是/logo/img001.png这种,路径不完整,咱们存储的路径上/media/logo/img001.png

   但到这里仍是不能正常显示图片,会显示404,是由于图片的url也是须要经过django进行指派,咱们还须要在urls.py进行设定。

  为了html模板能正确找到MEDIA_URL,TEMPLATES中导入相关的包。

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, 'templates')]
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
                'django.template.context_processors.media',#### add here
            ],
        },
    },
]

 

    直接参考官方文档便可。这样图片的url才是完整的,咱们的页面才能够正常显示图片。


 

2.  上传图片

  咱们可能须要用户上传本身的头像,或者相册,这里作一个简单的示范:

  首先须要一个form,enctype="multipart/form-data" method="post" 是必需要填写的,表示数据不通过编码,直接上传。{%csrf_token%}也是post时,django强制要求的。

<form enctype="multipart/form-data" action="#" method="post">
    {% csrf_token %}
    <input type="text" name="name">
    <input type="file" name="logo">

    <input type="submit" value="upload">
</form>

   而后须要去views.py对视图函数进行操做。

    if request.method == 'POST':
        file = request.FILES['logo']
        if file:
            new_img = Test(
                name=request.POST.get('name'),
                image=file

            )
            new_img.save()

   与普通的数据不一样,这里使用了request.FILES字典的方式去获取文件,而后建立新的数据,并保存到数据库中。

相关文章
相关标签/搜索