我正在编写一些有关通过django上传和显示图片的代码,但是我无法在网页上显示图片,上传功能可能是正确的。我尝试了许多解决方案,但没有一个可以工作。
class IMG(models.Model):
resumeImg=models.ImageField(upload_to='img')
CompanyName=models.CharField(max_length=200)
这些正在上传并显示功能:
def uploadImg(request):
if request.method=='POST':
new_img=IMG(
resumeImg=request.FILES.get('resumeImg'),
CompanyName=request.FILES.get('resumeImg').name
)
new_img.save()
return render(request,'lib/uploading.html')
def showImg(request):
imgs=IMG.objects.all()
content={'imgs':imgs}
for i in imgs:
print (i.resumeImg.url)
return render(request,'lib/showing.html',content)
网址是否有问题? 它是lib \ urls.py,lib是我的应用程序的名称:
urlpatterns = [
..........
path('upload/',views.uploadImg),
path('show/',views.showImg),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'lib/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/'
STATIC_ROOT = os.path.join(os.path.dirname(__file__), 'static')
MEDIA_ROOT = os.path.join(BASE_DIR,'lib\media').replace('\\','/')
MEDIA_URL='/media/'
STATICFILES_DIRS = (
('css', os.path.join(STATIC_ROOT, 'css').replace('\\', '/')),
('js', os.path.join(STATIC_ROOT, 'js').replace('\\', '/')),
('images', os.path.join(STATIC_ROOT, 'images').replace('\\', '/')),
('upload', os.path.join(STATIC_ROOT, 'upload').replace('\\', '/')),
)
这是关于HTML的代码。img.resumeImg.urls有什么问题吗?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
{% for img in imgs %}
<img src="{{ img.resumeImg.url }}"/>
{% endfor %}
</body>
</html>