我正在尝试制作一个函数,在上传之前调整图像大小。我在interent上发现了一些东西,它正在工作,但我想改进它。我不想有output_size=(320560([始终作为默认值],我想有一些django字段,并在每次需要时从django管理员处更改它。这就是我添加image_height
和image_width
字段的原因。
在我看来,这样做是解决方案output_size=(image_height,image_width(,但它不起的作用
output_size = (image_height, image_width)
NameError: name 'image_height' is not defined
如何使用image_height
和image_width
字段并使用将值添加到output_size
我的型号.py
from __future__ import unicode_literals
from django.db import models
from django.urls import reverse
from PIL import Image
def upload_location(instance, filename):
return "%s/%s" %('image/service', filename)
# Create your models here.
class Services(models.Model):
title = models.CharField(max_length=120)
content = models.TextField(null=True, blank=True)
image = models.ImageField(upload_to=upload_location, blank=True, null=True)
image_height = models.PositiveIntegerField(default=320)
image_width = models.PositiveIntegerField(default=560)
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.image.path)
if img.height > 320 or img.weight > 560:
output_size = (image_height, image_width)
img.thumbnail(output_size)
img.save(self.image.path)
def __unicode__(self):
return self.title
def __str__(self):
return self.title
使用self
class Services(models.Model):
# rest of your code
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
img = Image.open(self.image.path)
if img.height >320 or img.weight >560:
output_size = (self.image_height, self.image_width)
img.thumbnail(output_size)
img.save(self.image.path)