Search code examples
pythondjangofernet

Django Encrypt FileField with Fernet object has no attribute '_committed' occurred


I am passing multiple pdf uploads into the view from a form. (using Uppy.XHRUpload)

I want to encrypt them before saving them in the model.

When i test the files they can be encrypted and saved to a file and then read and decrptyped just fine.

But when I try to add to the model I get:

 'bytes' object has no attribute '_committed' occurred.

I can download enctryped file, re-read and then save but that would be a waste.

I thought it would be as simple as:

if request.method == 'POST' and request.FILES:

    files = request.FILES.getlist('files[]')

    for index, file in enumerate(files):

        f = Fernet(settings.F_KEY)

        pdf = file.read()
        encrypted = f.encrypt(pdf)

        PDF_File.objects.create(
            acct = a,
            pdf = encrypted
        )

The Model.

class PDF_File(models.Model):

     acct = models.ForeignKey(Acct, on_delete=models.CASCADE)
     pdf = models.FileField(upload_to='_temp/pdf/')

Thanks for your help.


Solution

  • it's cause you cannot save encrypted(bytes) to model

    try this

    from django.core.files.base import ContentFile
    
    for index, file in enumerate(files):
        f = Fernet(settings.F_KEY)
        pdf = file.read()
        encrypted = f.encrypt(pdf)
        content_file = ContentFile(encrypted, name=your_filename)
        PDF_File.objects.create(
            acct = a,
            pdf = content_file
        )
    

    ref from here https://docs.djangoproject.com/en/4.0/topics/http/file-uploads/