Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django ContentFile() unexpected empty line (django.core.files.base)

Tags:

python

django

I have a problem with the ContentFile function of django.core.files.base

I wrote a function that allows me to save text into an .md file

def save(title,content)
    filename = f"entries/{title}.md"
    if default_storage.exists(filename):
        default_storage.delete(filename)
    default_storage.save(filename, ContentFile(content))

I am using a simple textarea in a form that submits the content to the route that will save it.
The problem is that after saving every new line is duplicated:

Hello
World

Becomes

Hello

World

And this happens all the time. If you have 2 empty lines you end up having 4 of them...

Am I doing something wrong?

like image 901
Ivan Taccadoli Avatar asked Dec 22 '25 01:12

Ivan Taccadoli


1 Answers

I solved it by changing the last line of the save_entry function to

default_storage.save(filename, ContentFile(content.encode('ascii')))

per this answer https://stackoverflow.com/a/4053205

like image 152
Pelux Avatar answered Dec 23 '25 15:12

Pelux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!