我有一个标准的Django表单,其中包含一个图片字段。当上传该图片时,我希望确保图片大小不超过300px x 300px。以下是我的代码:
def post(request):
if request.method == 'POST':
instance = Product(posted_by=request.user)
form = ProductModelForm(request.POST or None, request.FILES or None)
if form.is_valid():
new_product = form.save(commit=False)
if 'image' in request.FILES:
img = Image.open(form.cleaned_data['image'])
img.thumbnail((300, 300), Image.ANTIALIAS)
# this doesnt save the contents here...
img.save(new_product.image)
# ..because this prints the original width (2830px in my case)
print new_product.image.width
我面临的问题是,我不清楚如何将
Image
类型转换为ImageField类型。
form.save()
之后,它会根据您的设置将其放在媒体文件夹中的某个位置。那么,为什么您不能在那里更改它并重新保存它呢?您似乎是从响应中复制了一份。 - James Khoury