0

来自媒体的图像未在我的 django 应用程序的模板中打开。 以下是网址或我的项目

from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myroyalkennel', include('myroyalkennel.urls')),
] + static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) 

下面是我的settings.py

STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = '/media/' 
  • 下面是我的views.py*
def store (request):
    items = products.objects.all
    return render(request, "myroyalkennel/store.html", {"itms":items}) 

下面是我的模板:

<body>
    <table>
        <tr>
        <th>image</th>  
        <th>SERIAL NUMBER</th>    
        <th>SERIAL NUMBER</th>
        <th>PRODUCT NAME</th>
        <th>VARIENT</th>
        <th>MRP</th>
        <th>DISCOUNTED PRICE</th>
        <th>DISCOUNT PERCENT</th>
        <th>IN STOCK</th>
        </tr>
    {%if itms %}
    {% for item in itms %}
        <tr>
            <td>{{item.image.url}}</td>
            <td>{{item.Serial_number}}</td>
            <td>{{item.product_name}}</td>
            <td>{{item.Varient}}</td>
            <td>{{item.MRP}}</td>
            <td>{{item.Discounted_price}}</td>
            <td>{{item.Discount_percent}}</td>
            <td>{{item.In_Stock}}</td>
        </tr>
        {% endfor %}
        {% endif %}    
    </table>
</body>
  • 下面是我的模型 *
class products(models.Model):
    Serial_number = models.CharField(max_length=10)
    product_name = models.TextField()
    Varient = models.CharField(max_length=15)
    MRP = models.IntegerField()
    Discounted_price = models.IntegerField()
    Discount_percent = models.CharField(max_length=6)
    In_Stock = models.CharField(max_length=15)
    image = models.ImageField(upload_to="asset/image",default="")

    def __str__(self):
        return self.product_name

当我使用 {{ item.image.url}} 在模板中调用图像时,它会给出路径 /media/asset/image/rkci_logo.jpg 但图像不会打开。

4

1 回答 1

1

您只是将图像 url 打印到模板中。您应该定义一个img标签并将src属性设置为{{item.image.url}}.

尝试这个:

商店.html

<body>
    <table>
        <tr>
        <th>image</th>  
        <th>SERIAL NUMBER</th>    
        <th>SERIAL NUMBER</th>
        <th>PRODUCT NAME</th>
        <th>VARIENT</th>
        <th>MRP</th>
        <th>DISCOUNTED PRICE</th>
        <th>DISCOUNT PERCENT</th>
        <th>IN STOCK</th>
        </tr>
    {%if itms %}
    {% for item in itms %}
        <tr>
            <!-- see below -->
            <td><img src="{{item.image.url}}" /></td>
            <td>{{item.Serial_number}}</td>
            <td>{{item.product_name}}</td>
            <td>{{item.Varient}}</td>
            <td>{{item.MRP}}</td>
            <td>{{item.Discounted_price}}</td>
            <td>{{item.Discount_percent}}</td>
            <td>{{item.In_Stock}}</td>
        </tr>
        {% endfor %}
        {% endif %}    
    </table>
</body>
于 2020-11-24T14:05:10.800 回答