python - 在管理页面查看相册中的照片

标签 python django

我希望能够在管理页面中查看我相册中的所有照片。

我是 Django 新手,所以我不确定如何创建一个功能,在单击相册标题时将显示所有照片。我相信我必须对 AlbumAdmin 类做一些事情,但我不确定那会是什么。相册和图片之间是一对多的关系。我只想在单击并进入特定相册页面时抓取与该相册相关的所有图片

enter image description here enter image description here

目前,当我点击相册时,没有任何显示。在我的数据库中实际上有相册中的图片。

应用程序/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"]

最佳答案

此功能由 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 中。

关于python - 在管理页面查看相册中的照片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28315945/

相关文章:

Python 将 char * 作为参数传递给函数

python - 如何用 matplotlib 绘制二维数学向量?

django - unique_together 外键对象属性

mysql - Django ForeignKey(用户),自动完成

python - 从数据框中的数组制作散点图

python - 在 Python 中乘除非类型和整数

python - 字典更新序列元素#0的长度为1;加载页面时需要2

python - 如何在 wagtail cms 字段中包含上下文变量?

django - 如何在 Django Rest 框架中使用一对多模型

python-docx 用 MySQL 数据生成文档