Django: Saving an image file from a form
I want to save the image which as been uploaded via the PaletteGenForm as such:
#Form
class PaletteGenForm(forms.Form):
im = forms.ImageField(required=True)
#View
def palette_gen_view(request):
PATH_OF_IMAGE_TO_BE_PALETTED= MEDIA_ROOT+ "/tobesaved.png"
if request.method == 'POST':
form = PaletteGenForm(request.POST, request.FILES)
if form.is_valid():
im = Image.open(StringIO(request.FILES['im']['content']))
im.save(PATH_OF_IMAGE_TO_BE_PALETTED, "PNG")
#call some functions to generate pallete
return #returns the palette of the image.
else:
form = PaletteGenForm()
return ren开发者_如何转开发der_to_response('palette_generate.html', {'form': form,})
However here is my error when calling this URL:
'InMemoryUploadedFile' object is unsubscriptable
Try this:
im = Image.open(StringIO(request.FILES['im'].read()))
Not sure you need to wrap it in a StringIO at all. Try
im = Image.open(request.FILES['im']['content'])
try reading the data from form cleaned_data
im = Image.open(StringIO(form.cleaned_data['im'].read()))
for me this worked (didn't tried reading from the request)
精彩评论