我希望能够在管理页面中查看我相册中的所有照片。
我是Django的新手,所以我不确定如何创建一个功能,点击相册标题后会显示所有照片。我相信我必须对AlbumAdmin
课做些什么,但我不确定那会是什么。专辑和图片之间存在一对多的关系。当我点击并进入特定的专辑页面时,我只想抓住与该专辑相关的所有图片
当我点击相册时,目前没有显示任何内容。在我的数据库中,实际上有相册中的图片。
应用程序/ models.py:
from django.db import models
from django.contrib import admin
from PIL import Image
from Boothie.settings import MEDIA_ROOT
from django.conf import settings
import os.path
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):
search_fields = ["title"]
list_display = ["title"]
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):
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)
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"]
答案 0 :(得分:1)
此功能由inline admin classes提供。
class PhotoAdmin(admin.TabularInline):
model = Photo
class AlbumAdmin(admin.ModelAdmin):
search_fields = ["title"]
list_display = ["title"]
model = Album
inlines = [PhotoAdmin]
请注意,这些类应位于admin.py文件中,而不是models.py。