版本:
class Img(models.Model):
img_url = models.ImageField(upload_to='img') # upload_to指定图片上传的途径,如果不存在则自动创建
python manage.py makemigrations
python manage.py migrate
修该项目的settings.py文件
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', # 加载驱动
'NAME': 'imgs',# 数据库名
'USER': 'root',# mysql的用户名
'PASSWORD': '',# mysql的密码
'HOST': 'localhost', # 连接地址(本地的话使用localhost或者127.0.0.1)
'PORT': 3306 # 数据库服务的端口号
}
}
MEDIA_ROOT = os.path.join(BASE_DIR, 'media').replace('\\', '/') # media即为图片上传的根路径
MEDIA_URL = '/media/'
def uploadImg(request): # 图片上传函数
if request.method == 'POST':
img = Img(img_url=request.FILES.get('img'))
img.save()
return render(request, 'imgupload.html')
from imgTest.views import uploadImg # 添加
urlpatterns = [
path('admin/', admin.site.urls),
path('uploadImg/', uploadImg), # 新增
]
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片上传title>
head>
<body>
<form action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="img">
<input type="submit" value="上传">
form>
body>
html>
def showImg(request):
imgs = Img.objects.all() # 从数据库中取出所有的图片路径
context = {
'imgs' : imgs
}
return render(request, 'showImg.html', context)
from django.contrib import admin
from django.urls import path
from imgTest.views import uploadImg, showImg
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('uploadImg/', uploadImg),
path('showImg/', showImg)
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
<html lang="en">
<head>
<meta charset="UTF-8">
<title>图片展示title>
head>
<body>
{% for item in imgs %}
<img src="{{ item.img_url.url }}"><br/>
{% endfor %}
body>
html>