我试图提交包含一些文本字段和图像字段的表单。并将其另存为新的模型对象。不能让它工作,所以我现在从一开始就遍历各个部分..
如何在视图中处理(仅保存)图像区域?我需要写一个额外的处理程序吗?它不是模型形式,而是常规形式。 PIL / PIllow在哪里出现。我应该导入吗?我可以清理图像区吗?
我一直在尝试这个:
def UploadThis(request):
if request.method == 'POST':
form = TestForm(request.POST, request.FILES)
response = {}
if form.is_valid():
response["status"] = "OK"
justtesting = Newmodel()
cd = form.cleaned_data
justtesting.name = cd['name']
justtesting.type = cd['type']
justtesting.description = cd['description']
justtesting.picture = request.FILES['picture']
justtesting.save()
型号:
class Newmodel(models.Model):
name = models.CharField(max_length=50)
type = models.CharField(max_length=50)
description = models.CharField(max_length=140, blank=True)
picture = models.ImageField(upload_to='images/testfiles', blank=True)
def __unicode__(self):
return self.name
形式:
class TestForm(forms.Form):
name = forms.CharField(max_length=50)
type = forms.CharField(max_length=50)
description = forms.CharField(max_length=140)
picture = forms.ImageField()
def clean(self):
cleaned_data = self.cleaned_data
name = cleaned_data.get("name")
description = cleaned_data.get("description")
type = cleaned_data.get("type")
return cleaned_data
答案 0 :(得分:2)
您的错误是您尝试使用request.POST将图像分配给模型字段,当您确实需要像这样使用form.cleaned_data时:
justtesting.picture = form.cleaned_data['picture']
表单上的干净方法当前没有做任何事情。您可以使用类似这样的干净方法进行验证(尽管这不是必需的):
def clean_image(self):
image = self.cleaned_data.get['image']
if image:
# do some validation, if it fails
raise forms.ValidationError(u'Form error')
return image
有关验证图片大小的示例,请参阅此问题:https://stackoverflow.com/a/16425455/1744645
不需要使用PIL / Pillow,只有在需要某种形式的图像处理时才需要使用PIL / Pillow。您可以在模型上使用保存方法,例如调整图像大小:
def save(self,force_insert=False, force_update=False, *args, **kwargs):
# save everything else
super(Newmodel, self).save(force_insert, force_update)
if self.image:
if self.image.width > 300 or self.image.height > 300:
resize_image(self.image)
PIL / Pillow本身有以下可能感兴趣的基本操作:
img = PIL.open(PATH_TO_IMAGE)
img = img.resize((x, y), PIL.ANTIALIAS)
img = img.crop((0, 0, x, y))
img.save(path,quality=90)
但请参阅http://effbot.org/imagingbook/pil-index.htm了解完整文档。