使用HTML在管理中显示图像

时间:2015-02-04 01:19:45

标签: python django

我希望能够在点击thumbnailPhoto display时查看我上传的图片。目前,当我点击其中任何一个时,我会通过URL发送到我的主页:

http://127.0.0.1:8000/media/test111/tumblr_nfps7hMRXZ1sfie3io1_1280.jpg

或采用此格式

http://127.0.0.1:8000/media/albumname/filename

我不确定为什么我会使用这种格式的网址重新路由到我的主页

enter image description here

urls.py

urlpatterns = patterns('',
    url(r'^admin/', include(admin.site.urls)),
    url(r'', 'home.views.load_home_content', name='home'),

) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

我的媒体设置:

MEDIA_ROOT = os.path.join(BASE_DIR, "../media_root/Boothie/pics")
MEDIA_URL = '/media/'

我的app / model.py

from django.db import models
from django.contrib import admin
from PIL import Image
from Boothie.settings import MEDIA_ROOT, MEDIA_URL
from django.conf import settings
import os.path
from django.utils.html import format_html
from django.core.files.storage import FileSystemStorage
import re

from django.utils.safestring import mark_safe

class Album(models.Model):
    title = models.CharField(max_length=50, unique=True)

    def __str__(self):
        return self.title

    def images(self):
        lst = [x.photo for x in self.photo_set.all()]
        return lst

    def save(self, *args, **kwargs):
        rgx = re.search(r'.*\w', self.title)
        self.title = rgx.group(0).replace(" ", "_")
        super(Album, self).save(*args, **kwargs)


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

def upload_path(self, filename):
        title = self.album.title
        if " " in title:
            title.replace(" ", "_")
        return os.path.join(title, filename)


class Photo(models.Model):
    title = models.CharField(max_length=50, blank=True)
    album = models.ForeignKey(Album)
    photo = models.ImageField(upload_to=upload_path)
    upload = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title


    def size(self):
        # Photo size
        return "%s x %s" % (self.photo.width, self.photo.height)

    def thumbnail(self):
        thumbnail_html = "<a href=\"{0}{1}\"><img border=\"0\" alt=\"\" src=\"{2}{3}\" height=\"80\" /></a>".format(settings.MEDIA_URL, self.photo.name, settings.MEDIA_URL, self.photo.name)
        print settings.MEDIA_URL, settings.MEDIA_ROOT
        return thumbnail_html

    thumbnail.allow_tags = True

    def photo_name(self):
        return os.path.basename(MEDIA_ROOT + "/" + self.photo.name)

    def photo_display(photo):
        return mark_safe('<a href="%s">%s</a>' % (photo.photo.url, os.path.split(photo.photo.name)[1]))

class PhotoAdmin(admin.ModelAdmin):
    search_fields = ["title", "photo"]
    list_display = ["photo_display", "thumbnail", "title", "album", "size"]
    list_filter = ["album"]

1 个答案:

答案 0 :(得分:1)

我认为原因是url(r'', 'home.views.load_home_content', name='home'),r''匹配所有内容。 Django按顺序检查urlpatterns,不匹配r'^admin/'的所有内容都转到r'',这是您的主页。要解决此问题,请尝试r'^$'