在Django的ImageField中使用height_field和width_field属性

ron*_*184 11 django django-models

我有一个模特

class Anh_chi_tiet(models.Model):
    du_an       = models.ForeignKey(Du_an)
    title       = models.CharField(max_length=120)
    url         = models.ImageField(upload_to='images', height_field='50', width_field='100')
    url_detail  = models.ImageField(upload_to='images', height_field='200', width_field='400')
Run Code Online (Sandbox Code Playgroud)

我总是收到这个错误:

'Anh_chi_tiet' object has no attribute '100'
Run Code Online (Sandbox Code Playgroud)

似乎Django需要同一个表Anh_chi_tiet中的两个字段来保存height_field和width_field.

如何在不添加表格中的新字段的情况下直接设置这些值?

cza*_*aic 19

height_field 表示模型的属性,用于存储高度.

class Anh_chi_tiet(models.Model):

  url_height=models.PositiveIntegerField()
  url_width=models.PositiveIntegerField()
  url = models.ImageField(upload_to='images', height_field='url_height', width_field='url_width')
Run Code Online (Sandbox Code Playgroud)

注意 height_field='url_height'

  • 有什么方法可以直接设置height_field和width_field而无需创建url_height和url_width字段? (2认同)

mki*_*irk 5

我认为您误解了height_field和width_field属性的用途.

height_field不用于更改高度.它用于记录高度已经是什么.

这样你可以做类似的事情

<img src="..." height={{my_instance.my_height_field}} /> 
Run Code Online (Sandbox Code Playgroud)

无需读取文件.

如果您要调整通过ImageField上传的所有图像的大小,请在此处查看: 使用django调整图像大小?