我是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
Views.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 }}">
这有助于其他人,但仍然让我的页面显示破损的图像。我使用谷歌浏览器查看了源代码,发现路径是(特定于hoodie.jpg):
<img src="pic_folder/hoodie.jpg">
然后我尝试了另一种方法:
<img src="{% static 'pic_folder/image.jpg' %}">
这确实在我的浏览器中多次显示image.jpg!我找到的路径是:
<img src="/static/pic_folder/image.jpg">
我不知何故需要将这两种方法结合起来,以便将图像动态加载到网页中。有人能帮助我吗?
答案 0 :(得分:1)
Djangos static
模板标签,允许您传递变量,因此,如您所示 - 结合您的方法
<img src="{% static cloth.image.url %}">