如何使用Django中的模板显示图像

时间:2015-12-05 15:46:38

标签: python django

我正在使用以下两个网址,homepage.html和detail.html

创建一个应用

我想在homepage.html中显示primary_image,并将primary_image作为链接。

另外,我想显示primary_image和amp; detail.html中的secondary_Image

models.py

class News(models.Model):
    title = models.CharField("Title", max_length = 256)
    author_Detail = models.CharField("Author" , max_length = 128)
    date = models.DateTimeField("Published Date")
    primary_image = models.ImageField("Main Image ",upload_to = "static/uploadedImg/main",)
    secondary_Image = models.ImageField("Sub Image",upload_to = "static/uploadedImg/sub",)

settings.py

STATIC_URL = '/static/'

STATIC_ROOT = os.path.join(BASE_DIR,"static")

MEDIA_ROOT = os.path.join(BASE_DIR,'media')

MEDIA_URL = '/media/'

articles.html

<div id = "randomArticle">
    <div id = "randommainImage">
         <a href = "{{random_object.id}}"><img id = "randomImage"
              src = "{{random_object.primary_image}}" width ="800" height = "300" alt = "{{random_object.title}}"></a>
</div> 

我可以在以下路径“media / static / uploadedImg / main”中保存上传的图像,但我无法在模板中访问。

此外,我正在检查firebug,它显示以下路径“/media/static/uploadedImg/main/home_category_image01.jpg”

还在服务器中获得以下内容 “GET / media / static / uploadedImg / main / home_category_image01 .jpg.jpg HTTP / 1.1“404 2186

有人能帮助我吗?

1 个答案:

答案 0 :(得分:1)

在循环中:

<img src="{{ model.primary_image.url }}" alt="{{ model.title }}">
<img src="{{ model.secondary_image.url }}" alt="{{ model.title }}">