python - HTML Django 1.10 中模型中的图像

标签 python html django django-1.10

我是 Django (1.10) 的新手,所以请原谅。我正在尝试将我的模特衣服中的图像可视化。尝试创建某种小型网上商店来进行培训。

我的模型:

from __future__ import unicode_literals

from django.db import models
from django.utils import timezone

class Clothes(models.Model):
    user = models.ForeignKey('auth.User')
    title = models.CharField(max_length=200)
    description = models.TextField()
    image = models.ImageField(upload_to = '/pic_folder/', default = '/pic_folder/None/no-img.jpg')
    type_clothes = models.CharField(max_length=100)
    created_date = models.DateTimeField(
            default=timezone.now)
    published_date = models.DateTimeField(
            blank=True, null=True)

    class Meta:
        verbose_name = "Kleding"
        verbose_name_plural = "Kleding"

    def publish(self):
        self.published_date = timezone.now()
        self.save()

    def __str__(self):
        return self.title

View .py

from django.shortcuts import render
from django.utils import timezone
from .models import Clothes

def clothes_overview(request):
    clothes= Clothes.objects.filter(published_date__lte=timezone.now())
    return render(request, 'Clothes/clothes_overview.html', {'clothes' : clothes})

clothes_overview.html

{% load staticfiles %}
<html>
    <head>
        <title>WebShop</title>
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
        <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css">
        <link rel="stylesheet" href="{% static 'css/clothes.css' %}">
    </head>
    <body>
        <div>
            <h1><a href="/">Clothing WebShop</a></h1>
        </div>

        {% for cloth in clothes %}
            <div>
                <p>published: {{ cloth.published_date }}</p>
                <h1><a href="">{{ cloth.title }}</a></h1>
                // DISPLAY IMAGE HERE
                <p>{{ cloth.text|linebreaksbr }}</p>
            </div>
        {% endfor %}
    </body>
</html>

我尝试了一个通过搜索 Stack 找到的选项:

                <img src="{{ cloth.image.url }}">

这对其他人有所帮助,但仍然让我的页面显示损坏的图像。我使用 Google Chrome 查看源代码,发现路径是(特定于 hoodie.jpg):

<img src="pic_folder/hoodie.jpg">

然后我尝试了另一种方法:

                <img src="{% static 'pic_folder/image.jpg' %}">

这确实在我的浏览器中多次显示了 image.jpg!我找到的路径是:

<img src="/static/pic_folder/image.jpg">

我需要以某种方式结合这两种方法,以便将图像动态加载到网页中。有人可以帮助我吗?

最佳答案

Django static模板标签,允许您传入变量,因此按照您的建议 - 结合您的方法

<img src="{% static cloth.image.url %}">

关于python - HTML Django 1.10 中模型中的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42070925/

相关文章:

python - 从 .ui 自动完成

javascript - 如何设置这个 javascript 倒数计时器的样式

javascript - 如何在html5 Canvas 中制作可点击的点?

javascript - js如何计算上传速度

Python 基准测试 : Why for in loop is faster than simple while?

python - 列表列表更改意外地反射(reflect)在子列表中

javascript - 获取引用错误: appearance is not defined

从另一个域重定向时 Django session 被丢弃

python - Django模型实例具体代码

python - 我可以从单独的库向现有包添加模块吗?