Reputation: 183
I'm able to upload photos to the media folder just fine. My problem is I can't save them to a specific folder on upload. I want the image to be saved in a unique folder based on an id being passed into the django view. Below is the code that throws the following error:
views.py", line 90, in orderdetails settings.MEDIA_ROOT + '/orders/' + str(orderid) + '/' + image) TypeError: coercing to Unicode: need string or buffer, InMemoryUploadedFile found
if request.method == 'POST':
# Loop through our files in the files list uploaded
if not os.path.exists(settings.MEDIA_ROOT + '/orders/' + str(orderid)):
os.makedirs(settings.MEDIA_ROOT + '/orders/' + str(orderid))
for image in request.FILES.getlist('files[]'):
# Create a new entry in our database
new_image = UploadedImages(client_order=client, image=image.name)
# Save the image using the model's ImageField settings
filename, ext = os.path.splitext(image.name)
new_image.image.save("%s-%s%s" % (filename, datetime.datetime.now(), ext),
settings.MEDIA_ROOT + '/orders/' + str(orderid) + '/' + image)
new_image.save()
If i just use image it saves just find in the media folder. Which is the code below. I know I set a folder inside my model with upload_to. Even with that I'm unsure how to set it to a folder based off of the ordierid.
if request.method == 'POST':
# Loop through our files in the files list uploaded
if not os.path.exists(settings.MEDIA_ROOT + '/orders/' + str(orderid)):
os.makedirs(settings.MEDIA_ROOT + '/orders/' + str(orderid))
for image in request.FILES.getlist('files[]'):
# Create a new entry in our database
new_image = UploadedImages(client_order=client, image=image.name)
# Save the image using the model's ImageField settings
filename, ext = os.path.splitext(image.name)
new_image.image.save("%s-%s%s" % (filename, datetime.datetime.now(), ext), image)
new_image.save()
Upvotes: 0
Views: 3151
Reputation: 183
After a night of searching I was able to find a fix. I had to define the Upload path with a dynamic function then set the upload_to to that function.
def image_upload_path(instance, filename):
return settings.MEDIA_ROOT + '/orders/{0}/{1}'.format(instance.client_order.invoice, filename)
class UploadedImages(models.Model):
...
image = models.ImageField(upload_to=image_upload_path)
This fixed my image location being saved to the correct location.
Upvotes: 1
Reputation: 12983
You're trying to concatenate a string and a file object '/' + image
You probably want the name of the file here, so try '/' + image.name
That may return some additional path information, so you would have to strip that out to get just the file name.
Upvotes: 0