I have the following models.py
class Imageo(models.Model):
file = models.ImageField(upload_to='cropped_images')
uploaded = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.pk)
I would like to savemy file into my Imageo models but it is saving into my database some other folder, please look at the views.py file.
def con(request):
if request.method == 'POST':
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
image = Image.open(form.cleaned_data['file'])
image = image.resize((200, 200), PIL.Image.ANTIALIAS)
image = image.convert('RGB')
dt = image.save('resize.jpg')
# i would like to save resize.jpg into my models name called file
return HttpResponse('done')
else:
form = ImageForm()
img = Imageo.objects.latest('id')
return render(request, 'NEC/imgCon.html', {'form': form, 'img': img})
I’m not sure I understand what you’re asking here.
Uploaded files don’t get saved into the database. FileFields don’t contain the data, they contain the reference to where the file is stored.
now resize.jpg got save in folder, i need it to save into my models name file.
please help me with crop size 200*200 file save into file models, please –
When you upload a file, the file name used to store the file in the file system is not necessarily the name of the file as it was originally uploaded - it doesn’t need to be the same, and quite frequently, shouldn’t be the same.
Also, I don’t see where the .save
function for an Image
in Pillow
returns anything.
Therefore, I would expect after this line:
that dt
would be None
. (see PIL.Image - Pillow (PIL Fork) 10.1.0 documentation)
So, what I think you might need to do is define the file object before the save, use that file object in the save, and then update your Imageo.file
object with the reference to the new file you just created. (I would also use one of the system functions to allocate a randomly-named file to prevent overwriting an existing file.)