如何解决通过管理页面在模型中添加几张图片
您好,我正在创建一个网站,可以在其中添加多个事件的图片。对于我正在使用的方法,我觉得我要复制几行代码,这会很有效率。
我当前的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 举报,一经查实,本站将立刻删除。