首页 > 解决方案 > Django - 静态图像渲染

问题描述

我有一个模板应该呈现每个产品的图片。但结果 - 它的 URL 在路径中有额外的“静态”

像这样 - 127.0.0.1:8000/静态/静态/照片/product1.png。

它应该只是 127.0.0.1:8000/static/photos/product1.png

有没有办法正确地做到这一点?

model.py将其保存到“静态/照片”

class Product(models.Model):
    title = models.CharField(max_length=20)
    photo = models.ImageField(upload_to='static/photos', default='http://placehold.it/700x400')

视图.py

from django.shortcuts import render
# Create your views here.
from .models import Category, Product

def product_list(request):
    queryset = Product.objects.all()
    context = {"object_list": queryset}
    return render(request, "product_list.html", context)

template.html如下

{% load static %}

{% for instance in object_list %}
    <p><img src="{% static instance.photo %}" /></p>
{% endfor %}

标签: djangostaticdjango-templates

解决方案


改变这个

{% for instance in object_list %}
    <p><img src="{% static instance.photo %}" /></p>
{% endfor %}

 {% for instance in object_list %}
    <p><img src="{% static instance.photo.url %}" /></p>
 {% endfor %}

推荐阅读