Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 encrrypted(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/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading