在django

时间:2016-04-14 05:02:41

标签: python django

当我通过admin.py添加对象时,如何在添加对象之前执行额外的逻辑?

例如,我单击管理员中的ADD MEDIA按钮并添加媒体对象:

enter image description here

请注意Location下的值Video Intro。我希望这个值只出现一次。如果存在,请将另一个对象的Location值更改为None

我希望在添加新模型对象之前执行此逻辑。现在确定在哪里进行更改以及如何进行更改。

这是项目结构:

enter image description here

这是我的admin.py

class MediaAdmin(admin.ModelAdmin):
    search_fields = ["name", "file"]
    list_display = ("name", "media_type", "location", "url", "album", "display", "thumbnail", "filesize")

    def display(self, media_obj):
        return format_html('<a href="%s">%s</a>' % (media_obj.file.url, media_obj.file.name))

    def filesize(self, media_obj):
        return self.convert_size(media_obj.file.size)

    def convert_size(self, size):
        if (size == 0):
            return '0 B'
        size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB")
        i = int(math.floor(math.log(size,1024)))
        p = math.pow(1024,i)
        s = round(size/p,2)
        return '%s %s' % (s,size_name[i])

    def thumbnail(self, media_obj):
        # pdb.set_trace()
        # location = os.path.join(settings.MEDIA_URL, media_obj.file.name)
        location = media_obj.file.url
        thumbnail_html = "<a href=\"{0}\"><img border=\"0\" alt=\"\" src=\"{1}\" height=\"80\" /></a>".format(location, location)
        return format_html(thumbnail_html)


class MediaInline(admin.TabularInline):
    model = Media

class AlbumInline(admin.TabularInline):
    model = Album

admin.site.register(Media, MediaAdmin)
admin.site.register(Album)

这是我的models.py

class Media(models.Model):
    LOCATION = (
        ("video_intro", "Video Intro"),
        ("logo", "Logo"),
        (None, "")

    )

    TYPE = (
        ("video", "Video"),
        ("gif", "GIF"),
        ("picture", "Picture"),
        ("audio", "Audio")
    )
    name = models.CharField(max_length=50, blank=True)
    location = models.CharField(choices=LOCATION, default=None, max_length=500, null=True)
    uploaded = models.DateTimeField(auto_now_add=True)
    media_type = models.CharField(max_length=50, choices=TYPE, default=None)
    album = models.ForeignKey('Album', blank=True, null=True)
    file = models.FileField(upload_to="media/")
    url = models.CharField(max_length=2083, blank=True, null=True, default=None)
    description = models.TextField(blank=True)

    def __str__(self):
        return self.name

    class Meta:
        verbose_name_plural = "Media"

2 个答案:

答案 0 :(得分:1)

Use Unique Together模型元,因此您可以确定只有一个视频介绍。无论是通过前端还是管理界面添加它。

但我不认为此选项会强制执行下拉菜单。

答案 1 :(得分:1)

如果您想要自定义模型的新实例的创建(即表中的新记录),请自定义the save method of the model

调用save方法将(新的或修改的)实例存储到数据库中。您可以在那里执行任何其他处理以“挂钩”到该保存事件。