问题描述
我正在尝试提供一个在上传之前调整图像大小的功能。我在interent上发现了一些东西,它正在工作,但我想改进它。而不是使用 output_size =(320,560) [始终始终为默认值],我想拥有一些django字段,并在每次需要django admin进行更改时进行更改。这就是为什么我添加了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
我的 models.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)