Django照片应用程序不显示

时间:2013-02-24 06:13:42

标签: django

我正在使用这个光鸟教程制作照片应用程序。

问题是,我上传的图片。不会显示在页面上。 我之前从未在django中显示过图片,我认为问题在于配置

enter image description here

enter image description here

我的models.py

  from django.db import models
  from django.contrib.auth.models import User
  from django.contrib import admin
  from string import join
  import os
  from PIL import Image as PImage
  from mysite.settings import MEDIA_ROOT

  class Album(models.Model):
      title = models.CharField(max_length=60)
      public = models.BooleanField(default=False)
      def __unicode__(self):
          return self.title
      def images(self):
          lst = [x.image.name for x in self.image_set.all()]
          lst = ["<a href='/media/%s'>%s</a>" % (x, x.split('/')[-1]) for x in lst]
    return join(lst, ', ')
      images.allow_tags = True
  class Tag(models.Model):
      tag = models.CharField(max_length=50)
      def __unicode__(self):
          return self.tag

  class Image(models.Model):
      title = models.CharField(max_length=60, blank=True, null=True)
      image = models.FileField(upload_to="images/")
      tags = models.ManyToManyField(Tag, blank=True)
      albums = models.ManyToManyField(Album, blank=True)
      created = models.DateTimeField(auto_now_add=True)
      rating = models.IntegerField(default=50)
      width = models.IntegerField(blank=True, null=True)
      height = models.IntegerField(blank=True, null=True)
      user = models.ForeignKey(User, null=True, blank=True)
      def save(self, *args, **kwargs):
          """Save image dimensions."""
          super(Image, self).save(*args, **kwargs)
          im = PImage.open(os.path.join(MEDIA_ROOT, self.image.name))
          self.width, self.height = im.size
          super(Image, self).save(*args, ** kwargs)

      def size(self):
          """Image size."""
          return "%s x %s" % (self.width, self.height)

      def __unicode__(self):
          return self.image.name

      def tags_(self):
          lst = [x[1] for x in self.tags.values_list()]
          return str(join(lst, ', '))

      def albums_(self):
          lst = [x[1] for x in self.albums.values_list()]
          return str(join(lst, ', '))

      def thumbnail(self):
          return """<a href="/media/%s"><img border="0" alt="" src="/media/%s" height="40" /></a>""" % (
                                                                (self.image.name, self.image.name))
thumbnail.allow_tags = True
      def __unicode__(self):
          return self.image.name

  class AlbumAdmin(admin.ModelAdmin):
      search_fields = ["title"]
      list_display = ["title"]

我的views.py

  from django.http import HttpResponseRedirect, HttpResponse
  from django.shortcuts import get_object_or_404, render_to_response
  from django.contrib.auth.decorators import login_required
  from django.core.context_processors import csrf
  from django.core.paginator import Paginator, InvalidPage, EmptyPage
  from django.forms import ModelForm
  from mysite.settings import MEDIA_URL

  from photo.models import *

  def main(request):
      """Main listing."""
      albums = Album.objects.all()
      if not request.user.is_authenticated():
          albums = albums.filter(public=True)

      paginator = Paginator(albums, 10)
      try: page = int(request.GET.get("page", '1'))
      except ValueError: page = 1

      try:
          albums = paginator.page(page)
      except (InvalidPage, EmptyPage):
          albums = paginator.page(paginator.num_pages)

      for album in albums.object_list:
          album.images = album.image_set.all()[:4]

      return render_to_response("photo/list.html", dict(albums=albums, user=request.user,
          media_url=MEDIA_URL))

        class TagAdmin(admin.ModelAdmin):
            list_display = ["tag"]

        class ImageAdmin(admin.ModelAdmin):
            search_fields = ["title"]
            list_display = ["__unicode__", "title", "user", "rating", "size", "tags_", "albums_",
    "thumbnail", "created"]
            list_filter = ["tags", "albums", "user"]

            def save_model(self, request, obj, form, change):
                obj.user = request.user
                obj.save()

        admin.site.register(Album, AlbumAdmin)
        admin.site.register(Tag, TagAdmin)
        admin.site.register(Image, ImageAdmin)

1 个答案:

答案 0 :(得分:1)

好的,这就是为什么图片没有显示的问题。您调用错误并覆盖图像的路径。请记住,您已经在模型中添加了缩略图,因此在模板中只能放置:

<ul>
    {% for album in albums.object_list %}
    <div class="title">{{ album.title }} ({{ album.image_set.count }} images)</div>
        <ul>
            {% for img in album.images %}
                {{img.thumbnail}}
            {% endfor %}
        </ul>
    {% endfor %}
</ul>

这是正确的,但我的问题是当我测试它时,allow标签功能没有效果,因此输出是链接而不是图像。所以我修改了它并得到了图像显示。

{% for img in album.images %}
    <a href="{{MEDIA_URL}}{{ img.image}}">
        <img border="0" alt="" src="{{MEDIA_URL}}{{ img.image}}" />
    </a>
{% endfor %}