开始之前我们先确认环境中已经安装了Pillow,
如果没有安装,可以通过 `pip install Pillow` 来安装,这个是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',
]
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 manage.py makemigrations
python manage.py migrate
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')
# 项目根路径/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),
]
在templates文件下创建一个文件(最好是我们的app的名字,以此来把页面按app分开),比如叫app1,然后在app1文件下创建我们的前端页面。
<!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>
python manage.py createsuperuser
from django.contrib import admin
from app01.models import Userprofile
admin.site.register(Userprofile)
我们可以先用IP:Port/static/icon路径访问看下能不能直接加载图片