Django HTML 变量中的图像字段
Posted
技术标签:
【中文标题】Django HTML 变量中的图像字段【英文标题】:Imagefield in Django HTML Variable 【发布时间】:2020-11-08 15:56:03 【问题描述】:我是 Django 新手,正在尝试创建一个通过 Django Admin 上传图片的网站。
我正在尝试在我的 html 中查看上传到 Imagefield 中的图像。 但我就是无法让图像正常工作。
Banner.objects.all() 似乎无法获取位于媒体文件夹中的所有图像文件。
urls.py
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('blog.urls')),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
from django.db import models
from django.db.models.signals import pre_delete
from django.dispatch.dispatcher import receiver
from django.utils import timezone
from django.contrib.auth.models import User
from PIL import Image
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now) #auto_now=True //auto date
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Banner(models.Model):
title = models.CharField(max_length=100)
images = models.ImageField(upload_to='images',null=True,blank=True)
def __str__(self):
return self.title
views.py
from django.shortcuts import render
from django.views.generic import(
ListView,
DetailView
)
from .models import *
# Create your views here.
class PostListView(ListView):
model = Post
template_name = 'blog/home.html'
context_object_name = 'posts'
ordering = ['-date_posted'] #arrange date posted with latest on top
paginate_by = 6
def Banner_view(request):
banner = Banner.objects.all()
return render(request, 'blog/home.html','banner':banner)
settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static_root')
#uploaded file in base directory "media"
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
home.html
% for b in banner %
<div>
<img src=" b.images.url ">
</div>
% endfor %
【问题讨论】:
【参考方案1】:你应该这样写
您应该使用/
进行路径检测
images = models.ImageField(upload_to='images/', null=True,blank=True)
【讨论】:
以上是关于Django HTML 变量中的图像字段的主要内容,如果未能解决你的问题,请参考以下文章