通过管理页面在模型中添加几张图片

问题描述

您好,我正在创建一个网站,可以在其中添加多个事件的图片。对于我正在使用的方法,我觉得我要复制几行代码,这会很有效率。

我当前的models.py是

class Csr (models.Model):
    title = models.CharField(max_length=80)
    main_image = models.ImageField(upload_to="CSR")
    content = models.TextField()
    date_of_occurence = models.DateField()
    

    def save(self,*args,**kwargs):
        super().save()
        img = Image.open(self.main_image.path)
        width,height = img.size  # Get dimensions

        if width > 200 and height > 200:
            img.thumbnail((width,height))

        # check which one is smaller
        if height < width:
            # make square by cutting off equal amounts left and right
            left = (width - height) / 2
            right = (width + height) / 2
            top = 0
            bottom = height
            img = img.crop((left,top,right,bottom))
        elif width < height:
            # make square by cutting off bottom
            left = 0
            right = width
            top = 0
            bottom = width
            img = img.crop((left,bottom))

        if width > 200 and height > 200:
            img.thumbnail((200,200))

        img.save(self.main_image.path)

    
    def __str__(self):
        return f"{self.title}"

但是我希望models.py像这样...

class Csr (models.Model):
    title = models.CharField(max_length=80)
    main_image = models.ImageField(upload_to="CSR")
    content = models.TextField()
    date_of_occurence = models.DateField()
    image_event1 = models.ImageField(upload_to="CSR/events",blank=True)
    image_event2 = models.ImageField(upload_to="CSR/events",blank=True)
    image_event3 = models.ImageField(upload_to="CSR/events",blank=True)
    image_event4 = models.ImageField(upload_to="CSR/events",blank=True)
    image_event5 = models.ImageField(upload_to="CSR/events",blank=True)
    image_event6 = models.ImageField(upload_to="CSR/events",blank=True)
    image_event7 = models.ImageField(upload_to="CSR/events",blank=True)
    image_event8 = models.ImageField(upload_to="CSR/events",blank=True)

我不想重复执行代码“ def save(self,* args,** kwargs):”几次,因为这会使我的代码效率很低。

任何帮助将不胜感激。谢谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)