On Dec 2, 4:40 am, muzhig <arseniy.pota...@gmail.com> wrote: > Hi! I need to resize and make a stamp on uploaded images and only then > save a model. > I have a procedure, that processes incoming File: > > def processUploadedImage(file): > img = Image.open(file) > downsampleUploadedimage(img) > stampUploadedImage(img) > img.save(file, "JPEG") > > I tried to process UploadedFile directly from request.FILES, before > constructing and validating form: > > ... > processUploadedImage(request.FILES['file']) > form = ImageUpload(request.POST, request.FILES) > if form.is_valid(): #it always fails here, is_valid returns > False, if > I process UploadedFile > ... > else: > redirect('/failed') > ... > > After it failed, I also tried to process it in my ImageUpload.save() > method: > class ImageUpload(forms.ModelForm): > class Meta: > model = Image > fields = ["title", "file"] > > def save(self,user,commit=True,**params): > image = forms.ModelForm.save(self,commit=False)#construct an > instance from form fields > processUploadedImage(image.file) > > ...another fields initialization, such as user, > publication_date and > so on... > > #save into db(if commit is True) and return model instance > return forms.models.save_instance(self, image, > commit,construct=False) > but it fails, when processUploadedImage tries to save image into file. > It trows IOError "Bad file descriptor".. > > I know that I can process image after it saved into db, but I dont > want server to do unnecessary work: > read full sized file, copy it into storage, then again open file in > starage, process it, save... > > I want beautyfull solution :) > Upload -> Process ->Construct model -> Save
This, to me, is a perfect use case for a signal, most likely pre_save. I am still not sure if you wish to save the original or the processed image in your model, but you can do either by moving any processing code to a method that gets triggered right before Django tries to save your model. You don't need to override the save() method of your model, but you could do it there, too, if you wish. However, it looks like you are trying to do it by overriding the save() method of your ModelForm, which I would not do in this case, although you could make it work. The data you are trying to manipulate has nothing to do with the form itself, or other fields in the form, and thus (I think) would be better to do in one of the other places I mentioned above. -- You received this message because you are subscribed to the Google Groups "Django users" group. To post to this group, send email to django-us...@googlegroups.com. To unsubscribe from this group, send email to django-users+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/django-users?hl=en.