Django - AttributeError _committed - python

I have a form that saves an image, and everything is working fine, but I want to be able to crop the image. However, when I used Pillow to do this, I get a strange error that doesn't really give me much to go on.
Attribute error at /userprofile/addGame/
_committed
Looking further into the traceback, the following sections were highlighted:
I'm not really sure what this error means. I think it has something to do with the form.save(committed=False), and not being able to edit files after that point, but I'm not positive. I can edit the user after that line using form.user = request.user, so I think it's the fact that I'm trying to change the image getting uploaded that is part of the issue.

This is an old post but I recently experienced a similar problem.
The information in the question is somewhat incomplete but I had the same error.
Assuming the Error being
File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/PIL/Image.py", line 627, in __getattr__
raise AttributeError(name)
AttributeError: _committed
So the root problem lies with using PIL (Pillow). The function :
image = Image.open(self.cleaned_data['image'])
We wrongly assume that the object image would continue to have the
instance of image throughout the function(clean_image in my case).
So in my code structure,
def clean_image(self):
if self.cleaned_data['image']:
try:
image = Image.open(self.cleaned_data['image'])
image.verify()
except IOError:
raise forms.ValidationError(_('The file is not an image'))
return image
The error mentioned above is thrown after we execute this code. It is so because
After several of the other PIL(pillow) functions we use, we need to
open the file again. Check this out in pillow documentation
As in the code above(last line),
return image
doesn't really return anything.
To fix it
Simply add ,
image = self.cleaned_data['image']
before the return image line.
Code looks like,
except IOError:
raise forms.ValidationError(_('The file is not an image'))
image = self.cleaned_data['image']
return image

I had faced the same issue trying to save a model with an ImageFileField. My requirement was to save an image from a zip object.
Using pillow gave me the AttributeError: _committed error. Following is what worked for me:
from django.core.files.images import ImageFile
zf = zipfile.ZipFile(zip_file, mode='r')
image_list = zf.infolist()
Model.objects.create(img=ImageFile(zipObj.open(image_list[0])),
file_name=image_list[0].filename.split("/")[-1].strip(),
...)

Related

'str' object has no attribute 'open' in python

I have created a simple streamlit app which has two option one is file upload another one is capturing image
while trying to open the uploaded file i am getting an error 'str' object has no attribute 'open' .
I am not sure why the issue is occurring kindly let me know how to solve this so that i can move forward
import streamlit as st
import numpy as np
import cv2
from PIL import Image
Image = st.sidebar.selectbox(
'Choose your method',
('Upload','Capture'))
if Image == 'Upload':
uploaded_file = st.file_uploader("HI",type=['jpg','png','jpeg'])
if uploaded_file is not None:
image = Image.open(uploaded_file)
st.image(image,width=300)
else:
file_image = st.camera_input(label = "Take a pic of you to be sketched out")
You have here two Image keywords, one of them is the Image library you imported from PIL, and the other is the return from your selectbox, which is a string.
Since the second one is declared later, it has overridden the first one, thus giving you this error when you try to call open.
I suggest renaming the second one to anything else and it should work properly.

AttributeError: 'NoneType' object has no attribute 'copy' opencv error coming when running code [duplicate]

This question already has answers here:
Why do I get AttributeError: 'NoneType' object has no attribute 'something'?
(11 answers)
Closed last year.
I am having an issue with this Python code:
Code And Other Things
The Error Is:
Traceback (most recent call last):
File "C:\Users\thaku\Desktop\projects\pythoncode-tutorials-master\machine-learning\face-age-prediction\predict_age.py", line 156, in <module>
predict_age(image_path)
File "C:\Users\thaku\Desktop\projects\pythoncode-tutorials-master\machine-learning\face-age-prediction\predict_age.py", line 113, in predict_age
frame = img.copy()
AttributeError: 'NoneType' object has no attribute 'copy'
I Was trying opencv as learning python. the project was to predict age but as this error came my days are wasted so please help me..
To Run The Code: python .\predict_age.py /tmp
or some new errors come
def predict_age(input_path: str):
"""Predict the age of the faces showing in the image"""
# Read Input Image
img = cv2.imread(input_path)
# Take a copy of the initial image and resize it
frame = img.copy()
Seems your error happens here because img is None, so it has no method copy() to call.
You said you are running the code like this:
.\predict_age.py /tmp
I can see that the code initialises img with the input_path which is passed as sys.argv[1]. well, /tmp is not really an image, could you try passing an image like .\predict_age.py /tmp/my_image.png
The error means that the img variable from cv2.imread(input_path) is None. I.e., something went wrong with reading the image from input_path.
In your main code, you write
import sys
image_path = sys.argv[1]
predict_age(image_path)
So the image path is given by the first argument to the program. Are you running the code as python predict_age.py 3-people.jpg?

Python PPTX library issue - Replacing image in slides ('SlidePart' object has no attribute 'related_parts')

I use the PPTX library to automate the creation of a deck of slides on a weekly basis.
It was working really well until the last update of the library. As you can see below, I keep getting the following when updating the "image part" of the slides:
AttributeError: 'SlidePart' object has no attribute 'related_parts'
Here is my function for the image replacement:
def replace_img_slide(prs, slide_nbr, shape_nbr, img_path):
slide = prs.slides[slide_nbr]
img = slide.shapes[shape_nbr]
try:
imgPic = img._pic
except AttributeError:
raise AttributeError(
f"Error for slide: {slide_nbr}, shape: {shape_nbr}, path: {img_path}")
imgRID = imgPic.xpath('./p:blipFill/a:blip/#r:embed')[0]
imgPart = slide.part.related_parts[imgRID]
with open(img_path, 'rb') as f:
rImgBlob = f.read()
# replace
imgPart._blob = rImgBlob
return prs
I found some related subject and I understood that the "related_parts" is now obsolete in the new version of the library but I did not find how to solve it. Do you think you can help me with that please ?
Many thanks in advance for your help !
Just use part.related_part(imgRID) where you used to use part.related_parts[imgRID].
The latest version exposes that method (internally) rather than expose a dict-like object just to do that one job.

AttributeError: 'ResourceSummaryWriter' object has no attribute 'get_logdir'

I am trying to run some code written in tensorflow v1.0 in tensorflow 2.1 library package. So I have to rewrite some of the code. I have been facing some problem with one line of the codes
LOG_DIR='./'
summary_writer = tf.summary.FileWriter(LOG_DIR)
now I understand that in v2.0, tf.summary has been deprecated and I was to write the new code instead
summary_writer = tf.summary.create_file_writer(LOG_DIR)
but whenever i start to run
logdir = summary_writer.get_logdir()
It gives me an error of
AttributeError: 'ResourceSummaryWriter' object has no attribute 'get_logdir'
I search around and found no solution. What can be the problem? Isn't it just stating the LOG_DIR (which I have done)
Regards
I got the same error, after a long struggling with that, I just solved it.
I just modified the core source "~tensorboard/plugins/projector/init.py"
I got rid of lines 'logdir' and pass the log file path to "summary_writer"
------------------ "~tensorboard/plugins/projector/init.py----------------------
enter image description here
------------------ myapp.py--------------------------------
enter image description here

python, django: copy image

I created this function, to copy an image from a django-model to another django-model. The image has to be saved redundantly:
def __copy_file__(from_object,to_object,field):
attr = field.attname
try:
newpath = getattr(from_object,attr).path
dot_at = newpath.rfind(".")
while os.path.exists(newpath):
newpath = newpath[:dot_at] + "_" + newpath[dot_at:]
shutil.copyfile(getattr(from_object,attr).path, newpath)
getattr(to_object,attr).save(newpath, File(open(getattr(from_object,attr).path)))
return True
except ValueError:
return False
But this function creates somehow invalid files.. I can remember it worked one day, but i tested it today and it isn't working anymore..
Edit: Now i know that the function produces two images. One that works and one that doesn't. The line shutil.copyfile (etc) produces the working one and in the assignment getattr(to_object,attr).save (etc) the image gets saved again. So this is the problem. It should just be assigned, not copied again..
Can anybody help me? :)
the way I do it, assuming from_model and to_model are to models instances with an image ImageField:
def copy_image(from_model, to_model):
to_model.image.save(from_model.image.url.split('/')[-1],from_model.image.file,save=True)

Categories

Resources