Django - edit uploaded file Before final saving

Viewed 1128

i'm making a site for uploading and processing of files (mostly images but also other stuff). sometimes, some files need some editing before saving. i want edit the uploaded file before saving it to media dir (mostly to avoid IO interaction and only keep original file in memory and discard after saving edit version).

edit: so i thought i have to run the edit function in POST, and change information in request.FILES. but i failed, and don't know what to do anymore.

NOTE: i'm mostly looking for a way to do it via class views.

here's some code for reference:

The model:

class FilePatient(models.Model):
    file_imag = models.FileField(upload_to='')

The View:

class FileAddView(LoginRequiredMixin, UserPassesTestMixin, SuccessMessageMixin, CreateView):
    model = FilePatient
    fields = ['file_imag']

    def post(self, request, *args, **kwargs):
        if request.FILES['file_imag'].name.endswith('.png'):
            newFile=editFile(request.FILES['image_imag'])
            # what to do, what not to do

        return super().post(request, *args, **kwargs)
1 Answers

I hope the following will help you... this code "edits" the file by resizing the original file if it is too big. Based on working code, I substituted the vars you used in your question, not tested as below.

from pathlib import Path
import PIL
from six import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile

img = request.FILES['fileInput']
if img.name.endswith('.png'):
    fp = FilePatient.objects.get(...)  # get the object for uploading file

    img2 = PIL.Image.open(img)
    exif = img2.info['exif'] if 'exif' in img2.info else None

    max_hw = 800  # px width / height maximum
    width_percent = (max_hw/float(img2.size[0]))
    heigth_percent = (max_hw/float(img2.size[1]))
    min_wh_percent = float(min(width_percent, heigth_percent))
    if min_wh_percent <= 1:
        width_size = int((float(img2.size[0])*min_wh_percent))
        height_size = int((float(img2.size[1])*min_wh_percent))
        img2 = img2.resize((width_size, height_size), PIL.Image.ANTIALIAS)

    fp.file_imag = img2
    buffer = BytesIO()
    if exif:
        img2.save(buffer, format='JPEG', exif=exif, quality=90)
    else:
        img2.save(buffer, format='JPEG', quality=90)
    buffer.seek(0)

    fp.file_imag.name = Path(img.name).stem
    fp.file_imag = InMemoryUploadedFile(buffer,
                                        'ImageField',
                                        f"{fp.file_imag.name}.jpg",
                                        'image/jpeg',
                                        img2.size,
                                        "utf-8")
   fp.save()
Related