【问题标题】:How to show multiple images from models through loop in django templete如何通过 Django 模板中的循环显示来自模型的多个图像
【发布时间】:2018-09-11 20:56:50
【问题描述】:

我正在尝试创建一个页面,我可以使用 Django 模型中的循环从我的数据模型中显示带有图像的产品详细信息,但是当我进入项目列表时,它适用于除图像之外的详细信息,在图像部分,它显示 alt文本。请帮帮我。

我的模型:

class Category(models.Model):
    name = models.CharField(max_length=50)

    def __str__(self):
        return self.name


class Item(models.Model):
    name = models.CharField(max_length=150)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)
    is_active = models.BooleanField(default=True)
    model_pic = models.ImageField(upload_to = 'static/media/')

    def __str__(self):
        return self.name

我的观点:

def item_list(request, category_id):
    category_name = Category.objects.get(pk=category_id)
    list_items = Item.objects.filter(category=category_name)
    context = {
       'list_items': list_items,
    }
    return render(request, 'inventory/item_list.html', context)

我的模板:

{% for item in list_items %}
       <tr>
           <td>{{ forloop.counter }}</td>
           <td>{{ item.name }}</td>
           <td>{{ item.category }}</td>
           <td>{{ item.is_active }}</td>
           <td><a href="{% url 'item_delete' item.pk %}">Delete</a></td>
           <td><img src="{{ item.model_pic.url }}" alt="Photo"></td>
        </tr>
 {% endfor %}

输出:enter image description here

【问题讨论】:

    标签: django image django-templates


    【解决方案1】:

    如果在开发过程中发生这种情况,请确保您的应用程序已配置为提供媒体服务。更新您的网址配置。例如:

    from django.conf import settings
    from django.conf.urls.static import static
    
    urlpatterns = [
        # ... the rest of your URLconf goes here ...
    ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    

    有关详细信息,请参阅:

    https://docs.djangoproject.com/en/2.1/howto/static-files/#serving-files-uploaded-by-a-user-during-development

    如果已配置,请检查文件的来源以查看显示的内容。 “照片”正在显示,因为网络浏览器无法找到该图像。

    【讨论】:

    • @MasudMorshed 将{{ MEDIA_URL }} 添加到您的链接中:src="{{ MEDIA_URL }}{{ item.model_pic.url }}"
    【解决方案2】:
    def item_list(request, category_id):
        category_name = Category.objects.get(pk=category_id)
        list_items = Item.objects.filter(category=category_name)
        context = {
           'list_items': list_items,
        }
        return render(request, 'inventory/item_list.html', context)
    

    这里的上下文字典将被分配到对应的 url item_list.html

    在设置中,一旦完成,您必须对静态参数进行 decalre; 在 item_list.html 中。你必须使用 {% static %} 然后遍历您的上下文元素。 在

     <img src="{% static variable %}" %}>
    

    【讨论】:

      猜你喜欢
      • 2011-11-17
      • 1970-01-01
      • 2020-09-21
      • 1970-01-01
      • 2011-08-13
      • 2021-05-18
      • 2018-08-10
      • 1970-01-01
      • 2022-11-30
      相关资源
      最近更新 更多