前置步骤
setting.py文件配置:
添加app目录
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01',
]
添加media文件和路径
PROJECT_ROOT = os.path.abspath(os.path.join(os.path.dirname('__file__')))
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
app目录下models.py配置
from django.db import models # Create your models here. class Test(models.Model):
name = models.CharField(max_length=50)
image = models.ImageField(upload_to='logo/')
注意:
ImageField() 依赖 Pillow (pip install Pillow)
这里login是目录路径 完整的路径是 /media/logo/图片
这里图片可以通过Django admin后台直接添加
所有设置一下app里 admin.py文件
from django.contrib import admin
from app01.models import Test # Register your models here. admin.site.register(Test)
引入models 中的Test类 然后 admin.site.register(Test)
接着加载数据库 写入数据库
创建超级用户
然后就是正常的Django访问配置了:
urls.py配置
注意!!! 这里必须要添加static 目录,后端通过传递/media/logo/图片,而这里是将图片传递到前端浏览器,这样才能访问路径的图片
from django.contrib import admin
from django.urls import path
from app01 import views
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static urlpatterns = [
path('admin/', admin.site.urls),
url(r'index/', views.index),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py配置
from django.shortcuts import render,HttpResponse
from app01 import models # Create your views here. def index(request):
img = models.Test.objects.all()
# img = models.Test.objects.filter(id=1)[0].image.url
return render(request,'index.html',{'img':img})
从数据库中读取图片路径 然后传递到前端页面.
前端页面:
后台传递的若是: img = models.Test.objects.all()
前端则是:
<body>
{% for i in img %}
<img src="{{ i.image.url}}">
{% endfor %}
</body>
后台传递的若是:img = models.Test.objects.filter(id=1)[0].image.url
前端则是:
<body>
{{ img }}
</body>
测试:
添加图片以后再 访问index页面