Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在我的Django博客模板中呈现图像?_Django - Fatal编程技术网

如何在我的Django博客模板中呈现图像?

如何在我的Django博客模板中呈现图像?,django,Django,大家好,我有一个博客设置,我想添加一个图像或缩略图的能力,以包括在每个博客文章。我在获取文件和博客模板的位置以匹配并显示图像时遇到问题。我也很难将ImageWithThumbnail模型集成到条目模型中 post.html {% include 'head.html' %} {% include 'navbar.html' %} {% load staticfiles %} {% load django_markdown %} <div class="container">

大家好,我有一个博客设置,我想添加一个图像或缩略图的能力,以包括在每个博客文章。我在获取文件和博客模板的位置以匹配并显示图像时遇到问题。我也很难将ImageWithThumbnail模型集成到条目模型中

post.html

    {% include 'head.html' %}
{% include 'navbar.html' %}
{% load staticfiles %}

{% load django_markdown %}

<div class="container">

  <div class="post">
    <h2><a href="{% url "entry_detail" slug=object.slug %}">{{ object.title }}</a></h2>

    <p class="meta">
      {{ object.created }} |
      Tagged under {{  object.tags.all|join:", " }} <p> Created by
      {{ object.author }} </p>
    </p>
    {{ object.body|markdown }}
<img src="{% static "{{ STATIC_ROOT }}/media/tableau_public.jpg" %}" alt="My image"/>
{{ object.file }}


</div>


{% include 'footer.html' %}
view.py

from django.views import generic
from . import models


class BlogIndex(generic.ListView):
    queryset = models.Entry.objects.published()
    template_name = "blog.html"
    paginate_by = 3


class BlogDetail(generic.DetailView):
    model = models.Entry
    template_name = "post.html"
models.py

from django.db import models
from django.core.urlresolvers import reverse
from django.conf import settings


class Tag(models.Model):
    slug = models.SlugField(max_length=200, unique=True)

    def __str__(self):
        return self.slug


class EntryQuerySet(models.QuerySet):
    def published(self):
        return self.filter(publish=True)


class Entry(models.Model):
    title = models.CharField(max_length=200)
    name = models.CharField(max_length = 255)
    file = models.ImageField()
    thumbnail = models.ImageField(upload_to=settings.MEDIA_ROOT+"/%Y/%m/%d",max_length=500,blank=True,null=True)
    author = models.CharField(max_length=200, null=True)
    body = models.TextField()
    slug = models.SlugField(max_length=200, unique=True)
    publish = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    modified = models.DateTimeField(auto_now=True)
    tags = models.ManyToManyField(Tag)
    objects = EntryQuerySet.as_manager()

    def filename(self):
        return os.path.basename(self.file.name)



    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse("entry_detail", kwargs={"slug": self.slug})

    class Meta:
        verbose_name = "Blog Entry"
        verbose_name_plural = "Blog Entries"
        ordering = ["-created"]


class ImageWithThumbnail(models.Model):
     name = models.CharField(max_length = 255)
     image = models.ImageField(upload_to="/%Y/%m/%d",max_length=500,blank=True,null=True)
     thumbnail = models.ImageField(upload_to="/%Y/%m/%d",max_length=500,blank=True,null=True)

     def create_thumbnail(self):
         # original code for this method came from
         # http://snipt.net/danfreak/generate-thumbnails-in-django-with-pil/

         # If there is no image associated with this.
         # do not create thumbnail
         if not self.image:
             return

         from PIL import Image
         from cStringIO import StringIO
         from django.core.files.uploadedfile import SimpleUploadedFile
         import os

         # Set our max thumbnail size in a tuple (max width, max height)
         THUMBNAIL_SIZE = (200,200)

         DJANGO_TYPE = self.image.file.content_type

         if DJANGO_TYPE == 'image/jpeg':
             PIL_TYPE = 'jpeg'
             FILE_EXTENSION = 'jpg'
         elif DJANGO_TYPE == 'image/png':
             PIL_TYPE = 'png'
             FILE_EXTENSION = 'png'

         # Open original photo which we want to thumbnail using PIL's Image
         image = Image.open(StringIO(self.image.read()))

         # Convert to RGB if necessary
         # Thanks to Limodou on DjangoSnippets.org
         # http://www.djangosnippets.org/snippets/20/
         #
         # I commented this part since it messes up my png files
         #
         #if image.mode not in ('L', 'RGB'):
         #    image = image.convert('RGB')

         # We use our PIL Image object to create the thumbnail, which already
         # has a thumbnail() convenience method that contrains proportions.
         # Additionally, we use Image.ANTIALIAS to make the image look better.
         # Without antialiasing the image pattern artifacts may result.
         image.thumbnail(THUMBNAIL_SIZE, Image.ANTIALIAS)

         # Save the thumbnail
         temp_handle = StringIO()
         image.save(temp_handle, PIL_TYPE)
         temp_handle.seek(0)

         # Save image to a SimpleUploadedFile which can be saved into
         # ImageField
         suf = SimpleUploadedFile(os.path.split(self.image.name)[-1],
                 temp_handle.read(), content_type=DJANGO_TYPE)
         # Save SimpleUploadedFile into image field
         self.thumbnail.save('%s_thumbnail.%s'%(os.path.splitext(suf.name)[0],FILE_EXTENSION), suf, save=False)

     def save(self):
         # create a thumbnail
         self.create_thumbnail()

         super(ImageWithThumbnail, self).save()
任何帮助都将不胜感激

谢谢

您只需要:

<img src="{{ object.thumbnail.url }}" alt="My image"/>

请注意,
{%static'文件扩展名“%}
仅用于呈现静态文件

我建议与一起使用


您只需要在模型中使用一个图像字段,然后在渲染模板时将制作缩略图留给轻松的缩略图。

您好,我很累,但它对我不起作用。我将/media/更改为/static/并移动了文件,由于某些原因,模板无法识别/media/文件夹。如果调试:MEDIA\u URL='/MEDIA/'STATIC\u ROOT=os.path.join(os.path.dirname(BASE\u DIR),“STATIC”,“STATIC only”)MEDIA\u ROOT=os.path.join(os.path.dirname(BASE\u DIR),“STATIC”,“MEDIA”)STATIC文件\u DIRS=(os.path.join(os.path.dirname(BASE\u DIR),“STATIC”,“STATIC”),
<img src="{{ object.thumbnail.url }}" alt="My image"/>