DjangoのListViewでテンプレートに画像が表示されません
前提・実現したいこと
DjangoのListViewでテンプレートに画像が表示されません
発生している問題・エラーメッセージ
検証でhtmlを見たところ何故か<img>が表示されておりませんでした。
該当のソースコード
settings.py
STATIC_URL = '/static/' STATIC_ROOT =os.path.join(BASE_DIR,'staticfiles') STATICFILES_DIRS = [str(BASE_DIR / 'static')] MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/'
urls.py
from django.contrib import admin from django.urls import path, include from django.urls import path from . import settings from django.contrib.staticfiles.urls import static urlpatterns = [ path('admin/', admin.site.urls), path('account/', include('account.urls')), path('stores/', include('stores.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
views.py
class ProductListView(LoginRequiredMixin, ListView): model = Products template_name = os.path.join('stores', 'product_list.html')
product_list.html
<div class="row row-cols-1 row-cols-sm-2 row-cols-md-3 g-3"> {% for product in object_list %} <div class="col"> <div class="card shadow-sm"> <img class="bd-placeholder-img card-img-top" width="100%" height="225" role="img" src="{product.picture.url}" aria-label="Placeholder: Thumbnail" preserveAspectRatio="xMidYMid slice" focusable="false"> <div class="card-body"> <h5 class="card-title">{{ product.name }}</h5> <h3 class="card-title">{{ product.price }}円</h3> <p class="card-text">{{ product.item_description }}</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <button type="button" class="btn btn-sm btn-outline-secondary">詳しく見る</button> <button type="button" class="btn btn-sm btn-outline-secondary">買い物カゴに入れる</button> </div> </div> </div> </div> </div> {% endfor %} </div>
models.py
class Products(models.Model): name = models.CharField(max_length=50) price = models.IntegerField() item_description = models.CharField(max_length=1000) product_type = models.ForeignKey(ProductTypes, on_delete=models.CASCADE) seller_name = models.ForeignKey(SellerName, on_delete=models.CASCADE) class Meta: db_table = 'products' def __str__(self): return self.name class ProductPictures(models.Model): picture = models.FileField(upload_to='product_pictures') product = models.ForeignKey( Products, on_delete=models.CASCADE ) order = models.IntegerField() class Meta: db_table = 'product_pictures' ordering =['order'] def __str__(self): return self.product.name + ': ' + str(self.order)
回答1件
あなたの回答
tips
プレビュー