我可以在def函数中使用django fileds值吗?

问题描述

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

按照我的想法,这是解决方 output_size =(image_height,image_width),但是它不起作用

output_size = (image_height,image_width)
NameError: name 'image_height' is not defined

如何使用image_heightimage_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)