这是shop.html的代码(我试图在其中显示图像)。
<div class="container mt-4">
<div class="row">
{% for b in books|slice:":10" %}
<div class="col-lg-2 col-md-3 col-sm-4">
<div class="book-card">
<div class="book-card__book-front">
<img src={{MEDIA_URL}}{{b.cover.url}} alt="book-image">
</div>
</div>
<div class="book-card__title">
{{ b.title }}
</div>
</div>
</div>
</div>
{% endfor %}
</div>
</div>
这是我将书的封面与出版商的ID(名称)相对应的模型
def book_cover_path(instance, filename):
return os.path.join(
"covers", instance.publisher.user.username, str(
instance.pk) + '.' + filename.split('.')[-1]
)
class Book(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField('Title', max_length=255)
authors = models.ManyToManyField(Author, related_name='books_written')
publisher = models.ForeignKey(Publisher, on_delete=models.DO_NOTHING, related_name='books_published')
price = models.DecimalField('Price', decimal_places=2, max_digits=10)
description = models.TextField('Description')
upload_timestamp = models.DateTimeField('Uploading DateTime', auto_now_add=True)
categories = models.ManyToManyField(Category, related_name='book_category')
cover = models.ImageField(upload_to=book_cover_path, null=True,blank=True)
class Meta:
unique_together = ('title', 'publisher')
get_latest_by = '-upload_timestamp'
这是views.py中的视图
def shop(req):
bookz = Book.objects.order_by('title')
var = {'books': bookz, 'range': 10}
return render(req, 'bookrepo/shop.html', context=var)
这是settings.py中的媒体设置。
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
这是我的文件夹结构,我确实将封面放在media / covers / publisher / image.jpg中,即使我尝试过类似media / media / covers / publisher / image.jpg之类的东西
This is structure of media directory
我在django控制台中收到未找到的错误
cover = models.ImageField(upload_to='covers', null=True,blank=True)
答案 0 :(得分:0)
答案 1 :(得分:0)
替换此行
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
to
MEDIA_ROOT = os.path.join(BASE_DIR,'media/')
因为保存文件的目录是绝对路径。
并替换
<img src={{MEDIA_URL}}{{b.cover.url}} alt="book-image">
to
<img src="{{b.cover.url}}" alt="book-image">
并将这些行添加到项目url.py文件中
from django.conf import settings
from django.conf. urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)