# 7、Django图片上传前端显示



```
开始之前我们先确认环境中已经安装了Pillow,
如果没有安装,可以通过 `pip install Pillow` 来安装,这个是python的图像处理库
```

### 1. **数据库设置**

* 我们创建好项目后先在项目创建一个app

```python
python manage.py startapp app01


# 然后将其加入到settings.py文件中
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app01',
]
```

### 2. **数据库中建立保存图片的表**

```python
from django.db import models

class Userprofile(models.Model):
    name = models.CharField(max_length=20)
    icon = models.ImageField(upload_to="uploads/%Y/%m/%d",verbose_name="用户头像")

    class Meta:
        db_table = 'userprofile'
        verbose_name = '用户表'
        verbose_name_plural = verbose_name
```

> 这里的upload\_to是指定图片存储的文件夹名称，上传文件之后会自动创建
>
> 执行命令做数据迁移，在执行迁移文件在数据库中创建表。
>
> 此处我们使用django自带的数据库,你也可以自己在settings里面配置

```python
python manage.py makemigrations
python manage.py migrate
```

### 3. **修改settings.py**

* 只需要在最后的静态文件区加上下面两行代码

```python
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'
            ],
        },
    },
]



STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
MEDIA_URL = '/static/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')
```

### 4. **配置项目视图函数**

```python
# 项目根路径/urls.py
from django.conf.global_settings import MEDIA_ROOT
from django.contrib import admin
from django.urls import path, re_path, include
from django.views.static import serve

from app01.views import *

urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'media/(?P<path>.*)$', serve, {'document_root': MEDIA_ROOT}),   ## 加上这行
    path('app01/', include('app01.urls')),
]

# app01/urls.py
from django.conf.global_settings import MEDIA_ROOT
from django.contrib import admin
from django.urls import path, re_path
from django.views.static import serve

from app01.views import index

urlpatterns = [
    path('index',index),
]
```

### 5. **创建模板**

> 在templates文件下创建一个文件（最好是我们的app的名字，以此来把页面按app分开），比如叫app1，然后在app1文件下创建我们的前端页面。

* index.html

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>aaaaaaa</h1>
    <!-- 这里需要添加 MEDIA_URL -->
<img src={{ MEDIA_URL }}{{ url }} alt="test">
</body>
</html>
```

### 6. **创建admin后台账号**

```python
python manage.py createsuperuser
```

### 7. **定义admin后台**

* admin.py

```python
from django.contrib import admin

from app01.models import Userprofile

admin.site.register(Userprofile)
```

### 8. **访问admin后台**

![](https://2134947750-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvILwbD2PrkBCkSitM3m4%2Fuploads%2FdvEQZmbRX6rYIBUgiSLI%2F1871335-20200626014507861-803934198.png?alt=media\&token=325d84cc-5607-49c7-8456-4c97398dcfba)

![](https://2134947750-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvILwbD2PrkBCkSitM3m4%2Fuploads%2FDw1zXhvjIwguqNS4yQ14%2F1871335-20200626014521996-607640393.png?alt=media\&token=5d5d0bcc-22c3-41f9-9916-b6e4253472fa)

### 9. **验证前端图片访问**

* 我们先去数据库表看一下对应的url路径

![](https://2134947750-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvILwbD2PrkBCkSitM3m4%2Fuploads%2FwsB0dh0qy833PCTNg3Ov%2F1871335-20200626014535513-79928398.png?alt=media\&token=f530ab53-1d1e-441b-ba25-552d360464eb)

```
我们可以先用IP:Port/static/icon路径访问看下能不能直接加载图片
```

![](https://2134947750-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FvILwbD2PrkBCkSitM3m4%2Fuploads%2FmtdNppkvQdlB7kLm3NRA%2F1871335-20200626014637837-1382482181.png?alt=media\&token=53565081-a635-4c36-92b3-04cadab35640)
