1、首先,附上参考文章链接地址:https://www.jianshu.com/p/32c52066ddb4 , 我版本是Django2的
2、settings 设置,查看底下有没有相关的配置和代码:
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# 上传的文件
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
3、参考文章底下说要在setting.py配置模板,但是我好像没配置:
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',
],
},
},
]
4、urls 配置:
from django.urls import path, re_path
from django.views.static import serve
from factoringms.settings import MEDIA_ROOT
app_name = 'user'
urlpatterns = [
re_path(r'^media/(?P<path>.*)$', serve, {'document_root': MEDIA_ROOT}),
]
5、views配置,其中读取之前上传的文件路径还有文件描述等等:
def user_auth_info(request, uid):
"""
用户实名认证审核信息
:param request:
:return:
"""
user = UserBase.objects.get(id=uid)
identify_file = UserIdentifyFile.objects.filter(user_id=uid)
url = request._get_scheme() + '://' + request.get_host() + '/user/user_info/media/'
file_path = identify_file[0].filepath
file_path = url + file_path
identify_desc = identify_file[0].identifydesc
content = {'user': user, 'uid': uid, 'file_path': file_path, 'identify_desc': identify_desc}
return render(request, 'user/user_info/user_auth_info.html', content)
6、之后html可以这样写:
<img src="{{ file_path }}">
7、可以试下访问这张图片的路径,如果访问不到展示不了图片,就证明路径出错,哪里有问题,就要在检查一下咯。
http://127.0.0.1:8000/user/user_info/media/user/user_info/auth/user.png
以上内容仅供学习参考,谢谢!