Django Resize image in Forms












0















I'm using python 3.6 and Django 2.0.



I have a square image that I want uploaded to a model. I currently have an image field in a model that I can upload.



avatar             = models.ImageField(path_and_rename, max_length=255, blank=True


I want to resize whatever square image is uploaded to be 750 by 750. I thought of a way to do it, but I don't think I'm saving it as the right type as it is giving me an error.



'Image' object has no attribute '_committed'


How can I resize my square image to meet the new dimensions that I need.



My code (leaving out validation to make it simpler):



forms.py



def clean_avatar(self):
avatar = self.cleaned_data['avatar']
try:
print(len(avatar))
w, h = get_image_dimensions(avatar)
max_width = max_height = 750
image = Image.open(avatar)
resized_image = image.resize((max_width,max_height), Image.ANTIALIAS)
print(type(avatar))
print(type(image))
print(type(resized_image))
return resized_image
except
...


the output of the above is



<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
<class 'PIL.JpegImagePlugin.JpegImageFile'>
<class 'PIL.Image.Image'>


if I return avatar it works, but it doesnt' work when I return resized_image. How can I make the datatype of resized_image that of avatar?



Full error message:



File "C:myapplibsite-packagesdjangocorehandlersexception.py" in inner


35. response = get_response(request)

File "C:myapplibsite-packagesdjangocorehandlersbase.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)

File "C:myapplibsite-packagesdjangocorehandlersbase.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:myapplibsite-packagesdjangoviewsgenericbase.py" in view
69. return self.dispatch(request, *args, **kwargs)

File "C:myapplibsite-packagesdjangocontribauthmixins.py" in dispatch
52. return super().dispatch(request, *args, **kwargs)

File "C:myapplibsite-packagesdjangoviewsgenericbase.py" in dispatch
89. return handler(request, *args, **kwargs)

File "C:myapplibsite-packagesdjangoviewsgenericedit.py" in post
194. return super().post(request, *args, **kwargs)

File "C:myapplibsite-packagesdjangoviewsgenericedit.py" in post
142. return self.form_valid(form)

File "C:myapplibsite-packagesdjangoviewsgenericedit.py" in form_valid
125. self.object = form.save()

File "C:myapplibsite-packagesdjangoformsmodels.py" in save
456. self.instance.save()

File "C:myapplibsite-packagesdjangocontribauthbase_user.py" in save
73. super().save(*args, **kwargs)

File "C:myapplibsite-packagesdjangodbmodelsbase.py" in save
729. force_update=force_update, update_fields=update_fields)

File "C:myapplibsite-packagesdjangodbmodelsbase.py" in save_base
759. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "C:myapplibsite-packagesdjangodbmodelsbase.py" in _save_table
820. for f in non_pks]

File "C:myapplibsite-packagesdjangodbmodelsbase.py" in <listcomp>
820. for f in non_pks]

File "C:myapplibsite-packagesdjangodbmodelsfieldsfiles.py" in pre_save
285. if file and not file._committed:

Exception Type: AttributeError at /account/details/
Exception Value: 'Image' object has no attribute '_committed'









share|improve this question























  • DO you want to resize image automatically or you want to give user the option which part of the image they want to choose?

    – Bidhan Majhi
    Nov 21 '18 at 5:41











  • Image.open returns a PIL.Image.Image object from (presumably) a str object which is a file name. What you probably need is to create a file using .save with a suitable str as a temporary name and then pass that.

    – Kapil
    Nov 21 '18 at 5:42











  • @BidhanMajhi I have some react code that will let the user crop the photo as they desire. Then I want to have them upload it where it will then be resized.

    – Micah Pearce
    Nov 21 '18 at 5:45













  • @Kapil do I save it in the forms section or do I save else (the view?)

    – Micah Pearce
    Nov 21 '18 at 5:46
















0















I'm using python 3.6 and Django 2.0.



I have a square image that I want uploaded to a model. I currently have an image field in a model that I can upload.



avatar             = models.ImageField(path_and_rename, max_length=255, blank=True


I want to resize whatever square image is uploaded to be 750 by 750. I thought of a way to do it, but I don't think I'm saving it as the right type as it is giving me an error.



'Image' object has no attribute '_committed'


How can I resize my square image to meet the new dimensions that I need.



My code (leaving out validation to make it simpler):



forms.py



def clean_avatar(self):
avatar = self.cleaned_data['avatar']
try:
print(len(avatar))
w, h = get_image_dimensions(avatar)
max_width = max_height = 750
image = Image.open(avatar)
resized_image = image.resize((max_width,max_height), Image.ANTIALIAS)
print(type(avatar))
print(type(image))
print(type(resized_image))
return resized_image
except
...


the output of the above is



<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
<class 'PIL.JpegImagePlugin.JpegImageFile'>
<class 'PIL.Image.Image'>


if I return avatar it works, but it doesnt' work when I return resized_image. How can I make the datatype of resized_image that of avatar?



Full error message:



File "C:myapplibsite-packagesdjangocorehandlersexception.py" in inner


35. response = get_response(request)

File "C:myapplibsite-packagesdjangocorehandlersbase.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)

File "C:myapplibsite-packagesdjangocorehandlersbase.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:myapplibsite-packagesdjangoviewsgenericbase.py" in view
69. return self.dispatch(request, *args, **kwargs)

File "C:myapplibsite-packagesdjangocontribauthmixins.py" in dispatch
52. return super().dispatch(request, *args, **kwargs)

File "C:myapplibsite-packagesdjangoviewsgenericbase.py" in dispatch
89. return handler(request, *args, **kwargs)

File "C:myapplibsite-packagesdjangoviewsgenericedit.py" in post
194. return super().post(request, *args, **kwargs)

File "C:myapplibsite-packagesdjangoviewsgenericedit.py" in post
142. return self.form_valid(form)

File "C:myapplibsite-packagesdjangoviewsgenericedit.py" in form_valid
125. self.object = form.save()

File "C:myapplibsite-packagesdjangoformsmodels.py" in save
456. self.instance.save()

File "C:myapplibsite-packagesdjangocontribauthbase_user.py" in save
73. super().save(*args, **kwargs)

File "C:myapplibsite-packagesdjangodbmodelsbase.py" in save
729. force_update=force_update, update_fields=update_fields)

File "C:myapplibsite-packagesdjangodbmodelsbase.py" in save_base
759. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "C:myapplibsite-packagesdjangodbmodelsbase.py" in _save_table
820. for f in non_pks]

File "C:myapplibsite-packagesdjangodbmodelsbase.py" in <listcomp>
820. for f in non_pks]

File "C:myapplibsite-packagesdjangodbmodelsfieldsfiles.py" in pre_save
285. if file and not file._committed:

Exception Type: AttributeError at /account/details/
Exception Value: 'Image' object has no attribute '_committed'









share|improve this question























  • DO you want to resize image automatically or you want to give user the option which part of the image they want to choose?

    – Bidhan Majhi
    Nov 21 '18 at 5:41











  • Image.open returns a PIL.Image.Image object from (presumably) a str object which is a file name. What you probably need is to create a file using .save with a suitable str as a temporary name and then pass that.

    – Kapil
    Nov 21 '18 at 5:42











  • @BidhanMajhi I have some react code that will let the user crop the photo as they desire. Then I want to have them upload it where it will then be resized.

    – Micah Pearce
    Nov 21 '18 at 5:45













  • @Kapil do I save it in the forms section or do I save else (the view?)

    – Micah Pearce
    Nov 21 '18 at 5:46














0












0








0








I'm using python 3.6 and Django 2.0.



I have a square image that I want uploaded to a model. I currently have an image field in a model that I can upload.



avatar             = models.ImageField(path_and_rename, max_length=255, blank=True


I want to resize whatever square image is uploaded to be 750 by 750. I thought of a way to do it, but I don't think I'm saving it as the right type as it is giving me an error.



'Image' object has no attribute '_committed'


How can I resize my square image to meet the new dimensions that I need.



My code (leaving out validation to make it simpler):



forms.py



def clean_avatar(self):
avatar = self.cleaned_data['avatar']
try:
print(len(avatar))
w, h = get_image_dimensions(avatar)
max_width = max_height = 750
image = Image.open(avatar)
resized_image = image.resize((max_width,max_height), Image.ANTIALIAS)
print(type(avatar))
print(type(image))
print(type(resized_image))
return resized_image
except
...


the output of the above is



<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
<class 'PIL.JpegImagePlugin.JpegImageFile'>
<class 'PIL.Image.Image'>


if I return avatar it works, but it doesnt' work when I return resized_image. How can I make the datatype of resized_image that of avatar?



Full error message:



File "C:myapplibsite-packagesdjangocorehandlersexception.py" in inner


35. response = get_response(request)

File "C:myapplibsite-packagesdjangocorehandlersbase.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)

File "C:myapplibsite-packagesdjangocorehandlersbase.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:myapplibsite-packagesdjangoviewsgenericbase.py" in view
69. return self.dispatch(request, *args, **kwargs)

File "C:myapplibsite-packagesdjangocontribauthmixins.py" in dispatch
52. return super().dispatch(request, *args, **kwargs)

File "C:myapplibsite-packagesdjangoviewsgenericbase.py" in dispatch
89. return handler(request, *args, **kwargs)

File "C:myapplibsite-packagesdjangoviewsgenericedit.py" in post
194. return super().post(request, *args, **kwargs)

File "C:myapplibsite-packagesdjangoviewsgenericedit.py" in post
142. return self.form_valid(form)

File "C:myapplibsite-packagesdjangoviewsgenericedit.py" in form_valid
125. self.object = form.save()

File "C:myapplibsite-packagesdjangoformsmodels.py" in save
456. self.instance.save()

File "C:myapplibsite-packagesdjangocontribauthbase_user.py" in save
73. super().save(*args, **kwargs)

File "C:myapplibsite-packagesdjangodbmodelsbase.py" in save
729. force_update=force_update, update_fields=update_fields)

File "C:myapplibsite-packagesdjangodbmodelsbase.py" in save_base
759. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "C:myapplibsite-packagesdjangodbmodelsbase.py" in _save_table
820. for f in non_pks]

File "C:myapplibsite-packagesdjangodbmodelsbase.py" in <listcomp>
820. for f in non_pks]

File "C:myapplibsite-packagesdjangodbmodelsfieldsfiles.py" in pre_save
285. if file and not file._committed:

Exception Type: AttributeError at /account/details/
Exception Value: 'Image' object has no attribute '_committed'









share|improve this question














I'm using python 3.6 and Django 2.0.



I have a square image that I want uploaded to a model. I currently have an image field in a model that I can upload.



avatar             = models.ImageField(path_and_rename, max_length=255, blank=True


I want to resize whatever square image is uploaded to be 750 by 750. I thought of a way to do it, but I don't think I'm saving it as the right type as it is giving me an error.



'Image' object has no attribute '_committed'


How can I resize my square image to meet the new dimensions that I need.



My code (leaving out validation to make it simpler):



forms.py



def clean_avatar(self):
avatar = self.cleaned_data['avatar']
try:
print(len(avatar))
w, h = get_image_dimensions(avatar)
max_width = max_height = 750
image = Image.open(avatar)
resized_image = image.resize((max_width,max_height), Image.ANTIALIAS)
print(type(avatar))
print(type(image))
print(type(resized_image))
return resized_image
except
...


the output of the above is



<class 'django.core.files.uploadedfile.InMemoryUploadedFile'>
<class 'PIL.JpegImagePlugin.JpegImageFile'>
<class 'PIL.Image.Image'>


if I return avatar it works, but it doesnt' work when I return resized_image. How can I make the datatype of resized_image that of avatar?



Full error message:



File "C:myapplibsite-packagesdjangocorehandlersexception.py" in inner


35. response = get_response(request)

File "C:myapplibsite-packagesdjangocorehandlersbase.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)

File "C:myapplibsite-packagesdjangocorehandlersbase.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "C:myapplibsite-packagesdjangoviewsgenericbase.py" in view
69. return self.dispatch(request, *args, **kwargs)

File "C:myapplibsite-packagesdjangocontribauthmixins.py" in dispatch
52. return super().dispatch(request, *args, **kwargs)

File "C:myapplibsite-packagesdjangoviewsgenericbase.py" in dispatch
89. return handler(request, *args, **kwargs)

File "C:myapplibsite-packagesdjangoviewsgenericedit.py" in post
194. return super().post(request, *args, **kwargs)

File "C:myapplibsite-packagesdjangoviewsgenericedit.py" in post
142. return self.form_valid(form)

File "C:myapplibsite-packagesdjangoviewsgenericedit.py" in form_valid
125. self.object = form.save()

File "C:myapplibsite-packagesdjangoformsmodels.py" in save
456. self.instance.save()

File "C:myapplibsite-packagesdjangocontribauthbase_user.py" in save
73. super().save(*args, **kwargs)

File "C:myapplibsite-packagesdjangodbmodelsbase.py" in save
729. force_update=force_update, update_fields=update_fields)

File "C:myapplibsite-packagesdjangodbmodelsbase.py" in save_base
759. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)

File "C:myapplibsite-packagesdjangodbmodelsbase.py" in _save_table
820. for f in non_pks]

File "C:myapplibsite-packagesdjangodbmodelsbase.py" in <listcomp>
820. for f in non_pks]

File "C:myapplibsite-packagesdjangodbmodelsfieldsfiles.py" in pre_save
285. if file and not file._committed:

Exception Type: AttributeError at /account/details/
Exception Value: 'Image' object has no attribute '_committed'






django resize python-imaging-library






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 21 '18 at 5:29









Micah PearceMicah Pearce

462413




462413













  • DO you want to resize image automatically or you want to give user the option which part of the image they want to choose?

    – Bidhan Majhi
    Nov 21 '18 at 5:41











  • Image.open returns a PIL.Image.Image object from (presumably) a str object which is a file name. What you probably need is to create a file using .save with a suitable str as a temporary name and then pass that.

    – Kapil
    Nov 21 '18 at 5:42











  • @BidhanMajhi I have some react code that will let the user crop the photo as they desire. Then I want to have them upload it where it will then be resized.

    – Micah Pearce
    Nov 21 '18 at 5:45













  • @Kapil do I save it in the forms section or do I save else (the view?)

    – Micah Pearce
    Nov 21 '18 at 5:46



















  • DO you want to resize image automatically or you want to give user the option which part of the image they want to choose?

    – Bidhan Majhi
    Nov 21 '18 at 5:41











  • Image.open returns a PIL.Image.Image object from (presumably) a str object which is a file name. What you probably need is to create a file using .save with a suitable str as a temporary name and then pass that.

    – Kapil
    Nov 21 '18 at 5:42











  • @BidhanMajhi I have some react code that will let the user crop the photo as they desire. Then I want to have them upload it where it will then be resized.

    – Micah Pearce
    Nov 21 '18 at 5:45













  • @Kapil do I save it in the forms section or do I save else (the view?)

    – Micah Pearce
    Nov 21 '18 at 5:46

















DO you want to resize image automatically or you want to give user the option which part of the image they want to choose?

– Bidhan Majhi
Nov 21 '18 at 5:41





DO you want to resize image automatically or you want to give user the option which part of the image they want to choose?

– Bidhan Majhi
Nov 21 '18 at 5:41













Image.open returns a PIL.Image.Image object from (presumably) a str object which is a file name. What you probably need is to create a file using .save with a suitable str as a temporary name and then pass that.

– Kapil
Nov 21 '18 at 5:42





Image.open returns a PIL.Image.Image object from (presumably) a str object which is a file name. What you probably need is to create a file using .save with a suitable str as a temporary name and then pass that.

– Kapil
Nov 21 '18 at 5:42













@BidhanMajhi I have some react code that will let the user crop the photo as they desire. Then I want to have them upload it where it will then be resized.

– Micah Pearce
Nov 21 '18 at 5:45







@BidhanMajhi I have some react code that will let the user crop the photo as they desire. Then I want to have them upload it where it will then be resized.

– Micah Pearce
Nov 21 '18 at 5:45















@Kapil do I save it in the forms section or do I save else (the view?)

– Micah Pearce
Nov 21 '18 at 5:46





@Kapil do I save it in the forms section or do I save else (the view?)

– Micah Pearce
Nov 21 '18 at 5:46












1 Answer
1






active

oldest

votes


















0














I have done simillar thing, but not in forms. My approach was like this:



# override Model Save Method

class YourModel(models.Model):
...
def save(self, **kwargs):
resize = kwargs.pop('resize', False)
instance = super(YourModel, self).save(**kwargs)
if resize:
pil_image = Image.open(self.avatar.path)
# resize related code
resized_image = pil_image.resize((max_width,max_height), Image.ANTIALIAS)
resized_image.save(self.avatar.path)

return instance


And call this save method from form like this:



 class YourForm(...):
...
def save(self, commit=True):
instance = super(YourForm, self).save(commit=False)
instance.save(resize=True) # call model save method from here
return instance


Update



Maybe you can try like this:



import io 

# clean method
w, h = get_image_dimensions(avatar)
max_width = max_height = 750
image = Image.open(avatar)
resized_image = image.resize((max_width,max_height), Image.ANTIALIAS)
img_in_memory = io.BytesIO()
resized_image.save(img_in_memory, format="png")
return img_in_memory





share|improve this answer


























  • I tried this and for this line pil_image = Image.open(self.avatar.path) I got an error message - this back end doesn't support absolute paths. I'm using s3 to save my files. Gonna look into this tomorrow.

    – Micah Pearce
    Nov 21 '18 at 6:41











  • I saw another post say to change it to self.avatar.name, but when I do it says that the file doesn't exist (cause I haven't saved it yet). Confusing.

    – Micah Pearce
    Nov 21 '18 at 6:50











  • @MicahPearce please see my answer's update section. Hope it helps!!

    – ruddra
    Nov 21 '18 at 7:54













Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53405755%2fdjango-resize-image-in-forms%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














I have done simillar thing, but not in forms. My approach was like this:



# override Model Save Method

class YourModel(models.Model):
...
def save(self, **kwargs):
resize = kwargs.pop('resize', False)
instance = super(YourModel, self).save(**kwargs)
if resize:
pil_image = Image.open(self.avatar.path)
# resize related code
resized_image = pil_image.resize((max_width,max_height), Image.ANTIALIAS)
resized_image.save(self.avatar.path)

return instance


And call this save method from form like this:



 class YourForm(...):
...
def save(self, commit=True):
instance = super(YourForm, self).save(commit=False)
instance.save(resize=True) # call model save method from here
return instance


Update



Maybe you can try like this:



import io 

# clean method
w, h = get_image_dimensions(avatar)
max_width = max_height = 750
image = Image.open(avatar)
resized_image = image.resize((max_width,max_height), Image.ANTIALIAS)
img_in_memory = io.BytesIO()
resized_image.save(img_in_memory, format="png")
return img_in_memory





share|improve this answer


























  • I tried this and for this line pil_image = Image.open(self.avatar.path) I got an error message - this back end doesn't support absolute paths. I'm using s3 to save my files. Gonna look into this tomorrow.

    – Micah Pearce
    Nov 21 '18 at 6:41











  • I saw another post say to change it to self.avatar.name, but when I do it says that the file doesn't exist (cause I haven't saved it yet). Confusing.

    – Micah Pearce
    Nov 21 '18 at 6:50











  • @MicahPearce please see my answer's update section. Hope it helps!!

    – ruddra
    Nov 21 '18 at 7:54


















0














I have done simillar thing, but not in forms. My approach was like this:



# override Model Save Method

class YourModel(models.Model):
...
def save(self, **kwargs):
resize = kwargs.pop('resize', False)
instance = super(YourModel, self).save(**kwargs)
if resize:
pil_image = Image.open(self.avatar.path)
# resize related code
resized_image = pil_image.resize((max_width,max_height), Image.ANTIALIAS)
resized_image.save(self.avatar.path)

return instance


And call this save method from form like this:



 class YourForm(...):
...
def save(self, commit=True):
instance = super(YourForm, self).save(commit=False)
instance.save(resize=True) # call model save method from here
return instance


Update



Maybe you can try like this:



import io 

# clean method
w, h = get_image_dimensions(avatar)
max_width = max_height = 750
image = Image.open(avatar)
resized_image = image.resize((max_width,max_height), Image.ANTIALIAS)
img_in_memory = io.BytesIO()
resized_image.save(img_in_memory, format="png")
return img_in_memory





share|improve this answer


























  • I tried this and for this line pil_image = Image.open(self.avatar.path) I got an error message - this back end doesn't support absolute paths. I'm using s3 to save my files. Gonna look into this tomorrow.

    – Micah Pearce
    Nov 21 '18 at 6:41











  • I saw another post say to change it to self.avatar.name, but when I do it says that the file doesn't exist (cause I haven't saved it yet). Confusing.

    – Micah Pearce
    Nov 21 '18 at 6:50











  • @MicahPearce please see my answer's update section. Hope it helps!!

    – ruddra
    Nov 21 '18 at 7:54
















0












0








0







I have done simillar thing, but not in forms. My approach was like this:



# override Model Save Method

class YourModel(models.Model):
...
def save(self, **kwargs):
resize = kwargs.pop('resize', False)
instance = super(YourModel, self).save(**kwargs)
if resize:
pil_image = Image.open(self.avatar.path)
# resize related code
resized_image = pil_image.resize((max_width,max_height), Image.ANTIALIAS)
resized_image.save(self.avatar.path)

return instance


And call this save method from form like this:



 class YourForm(...):
...
def save(self, commit=True):
instance = super(YourForm, self).save(commit=False)
instance.save(resize=True) # call model save method from here
return instance


Update



Maybe you can try like this:



import io 

# clean method
w, h = get_image_dimensions(avatar)
max_width = max_height = 750
image = Image.open(avatar)
resized_image = image.resize((max_width,max_height), Image.ANTIALIAS)
img_in_memory = io.BytesIO()
resized_image.save(img_in_memory, format="png")
return img_in_memory





share|improve this answer















I have done simillar thing, but not in forms. My approach was like this:



# override Model Save Method

class YourModel(models.Model):
...
def save(self, **kwargs):
resize = kwargs.pop('resize', False)
instance = super(YourModel, self).save(**kwargs)
if resize:
pil_image = Image.open(self.avatar.path)
# resize related code
resized_image = pil_image.resize((max_width,max_height), Image.ANTIALIAS)
resized_image.save(self.avatar.path)

return instance


And call this save method from form like this:



 class YourForm(...):
...
def save(self, commit=True):
instance = super(YourForm, self).save(commit=False)
instance.save(resize=True) # call model save method from here
return instance


Update



Maybe you can try like this:



import io 

# clean method
w, h = get_image_dimensions(avatar)
max_width = max_height = 750
image = Image.open(avatar)
resized_image = image.resize((max_width,max_height), Image.ANTIALIAS)
img_in_memory = io.BytesIO()
resized_image.save(img_in_memory, format="png")
return img_in_memory






share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 21 '18 at 7:54

























answered Nov 21 '18 at 5:48









ruddraruddra

15.2k32748




15.2k32748













  • I tried this and for this line pil_image = Image.open(self.avatar.path) I got an error message - this back end doesn't support absolute paths. I'm using s3 to save my files. Gonna look into this tomorrow.

    – Micah Pearce
    Nov 21 '18 at 6:41











  • I saw another post say to change it to self.avatar.name, but when I do it says that the file doesn't exist (cause I haven't saved it yet). Confusing.

    – Micah Pearce
    Nov 21 '18 at 6:50











  • @MicahPearce please see my answer's update section. Hope it helps!!

    – ruddra
    Nov 21 '18 at 7:54





















  • I tried this and for this line pil_image = Image.open(self.avatar.path) I got an error message - this back end doesn't support absolute paths. I'm using s3 to save my files. Gonna look into this tomorrow.

    – Micah Pearce
    Nov 21 '18 at 6:41











  • I saw another post say to change it to self.avatar.name, but when I do it says that the file doesn't exist (cause I haven't saved it yet). Confusing.

    – Micah Pearce
    Nov 21 '18 at 6:50











  • @MicahPearce please see my answer's update section. Hope it helps!!

    – ruddra
    Nov 21 '18 at 7:54



















I tried this and for this line pil_image = Image.open(self.avatar.path) I got an error message - this back end doesn't support absolute paths. I'm using s3 to save my files. Gonna look into this tomorrow.

– Micah Pearce
Nov 21 '18 at 6:41





I tried this and for this line pil_image = Image.open(self.avatar.path) I got an error message - this back end doesn't support absolute paths. I'm using s3 to save my files. Gonna look into this tomorrow.

– Micah Pearce
Nov 21 '18 at 6:41













I saw another post say to change it to self.avatar.name, but when I do it says that the file doesn't exist (cause I haven't saved it yet). Confusing.

– Micah Pearce
Nov 21 '18 at 6:50





I saw another post say to change it to self.avatar.name, but when I do it says that the file doesn't exist (cause I haven't saved it yet). Confusing.

– Micah Pearce
Nov 21 '18 at 6:50













@MicahPearce please see my answer's update section. Hope it helps!!

– ruddra
Nov 21 '18 at 7:54







@MicahPearce please see my answer's update section. Hope it helps!!

– ruddra
Nov 21 '18 at 7:54






















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53405755%2fdjango-resize-image-in-forms%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







這個網誌中的熱門文章

Xamarin.form Move up view when keyboard appear

Post-Redirect-Get with Spring WebFlux and Thymeleaf

Anylogic : not able to use stopDelay()