如何在djang的网页上显示图像(imagefield)

2024-10-04 09:32:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一些关于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)

url有什么问题吗? 它是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.url有什么问题吗


<!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>

can not see the image


Tags: pathdjangoimgosrequestlibhtmlcontext